Crontab Reboot_ How to Execute a Job Automatically at Boot?


Crontab is a widely used tool for scheduling tasks on Linux systems. It provides a simple way to automate routine tasks, such as backups, system maintenance, and data processing. However, crontab is limited to scheduling tasks based on a specific time or interval. What if you need to run a script only when certain conditions are met, such as when a file is created or when a process is running?

In this blog post, we will discuss how to use crontab to execute a job conditionally on a Linux system.

Step 1: Identify the Condition

The first step is to identify the condition that triggers the execution of the job. There are many conditions that can be used to trigger a job, such as the creation or modification of a file, the presence of a running process, or the state of a system service.

For example, let's say we want to execute a script only when a specific file is created in the /tmp directory. We can use the inotifywait command to monitor the /tmp directory for file creation events, and execute our script when a new file is detected.

Step 2: Create the Script

Next, we need to create the script that will be executed when the condition is met. In our example, the script should perform some action when a new file is created in the /tmp directory. For simplicity, let's create a script that just echoes a message to the terminal.

Create a new file called "myscript.sh" and add the following code −

#!/bin/bash echo "New file created in /tmp directory"

Save the file and make it executable −

chmod +x myscript.sh

Step 3: Monitor the Condition

Now we need to monitor the condition and execute our script when the condition is met. In our example, we want to monitor the /tmp directory for file creation events using the inotifywait command.

Open a new terminal window and type the following command −

inotifywait -m /tmp -e create --format '%w%f' | while read file; do /path/to/myscript.sh; done

This command will monitor the /tmp directory for file creation events and execute the "myscript.sh" script when a new file is created.

Let's break down this command −

  • The "-m" option tells inotifywait to monitor the directory continuously.

  • The "-e" option specifies the event we want to monitor, in this case "create".

  • The "--format" option specifies the output format of the event. In our example, we want to output the name of the file that was created.

  • The "|" symbol is a pipe, which sends the output of the inotifywait command to the next command in the pipeline.

  • The "while read" loop reads each line of output from inotifywait and executes the "myscript.sh" script.

Replace "/path/to/myscript.sh" with the actual path to your script.

Step 4: Schedule the Job

The final step is to schedule the job using crontab. We want our script to be executed only when the condition is met, so we will use a conditional statement to check whether the script should be executed.

Open the crontab file for editing −

crontab -e

Add the following line to the crontab file −

* * * * * /usr/bin/bash -c 'if [ -f /tmp/*.txt ]; then /path/to/myscript.sh; fi'

This line schedules the job to run every minute. The command first checks whether there is a file with the ".txt" extension in the /tmp directory. If such a file exists, the "myscript.sh" script is executed.

Let's break down this command −

  • The "*" symbols specify the time and date when the job should be executed. In this case, the job will run every minute.

  • The "/usr/bin/bash -c" part specifies the command to be executed. We need to use the full path to the bash executable to ensure that crontab can find it.

  • The "if [ -f /tmp/*.txt ]" part is a conditional statement that checks whether a file with the ".txt" extension exists in the /tmp directory.

  • The "then" keyword indicates that the script should be executed if the condition is true.

  • The "/path/to/myscript.sh" part specifies the path to our script.

Replace "/path/to/myscript.sh" with the actual path to your script.

Using advanced Crontab functions

While conditional job execution is a powerful feature of crontab, there are many other advanced features that can help you automate your Linux system. Here are a few examples −

  • Schedule jobs at specific times − By default, crontab schedules jobs to run at specific intervals (e.g., every minute, every hour, etc.). However, you can also schedule jobs to run at specific times of day, weeks, or months. For example, the following command will run a script at 3:30 AM every day −

30 3 * * * /path/to/script.sh
  • Run jobs with different priorities − By default, crontab runs all jobs with the same priority. However, you can use the "nice" command to run jobs with different levels of priority. For example, the following command will run a script with low priority −

0 0 * * * nice -n 19 /path/to/script.sh
  • Use environment variables and command-line options − You can use environment variables and command-line options to customize the behavior of your scripts. For example, you might set environment variables to configure database connection strings or use command-line options to control the behavior of your scripts. For example, the following command will run a script with a custom environment variable −

0 0 * * * ENV_VAR=value /path/to/script.sh

By exploring these advanced features of crontab, you can create more sophisticated automation workflows that respond to specific events and conditions.

Common Use Cases for Conditional Job Execution

While conditional job execution can be used for any task that depends on a specific condition, some use cases are more common than others. Here are a few examples −

  • Monitoring log files for errors − You can use conditional job execution to monitor log files for errors and send notifications when errors occur. For example, the following crontab command will run a script that checks the system log for errors every hour −

0 * * * * if grep -q error /var/log/syslog ; then /path/to/script.sh ; fi
  • Checking network services for availability − You can use conditional job execution to check network services for availability and send notifications when services go down. For example, the following crontab command will run a script that checks whether the Apache web server is running every five minutes −

*/5 * * * * if ! pgrep apache2 ; then /path/to/script.sh ; fi
  • Cleaning up old files − You can use conditional job execution to clean up old files and prevent disk space from filling up. For example, the following crontab command will delete any files in the /tmp directory that are more than seven days old −

0 0 * * * find /tmp -type f -mtime +7 -delete
  • Running backups − You can use conditional job execution to run backups when specific conditions are met (e.g., a certain amount of data has been added or modified). For example, the following crontab command will run a script that backs up a database whenever a certain number of rows have been added −

* * * * * if [ $(mysql -N -e "SELECT COUNT(*) FROM mytable;") -gt 1000 ]; then/path/to/backup.sh ; fi

By leveraging conditional job execution in these and other use cases, you can automate your Linux system and reduce the amount of manual work required to keep your system running smoothly.

Conclusion

In this blog post, we discussed how to use crontab to execute a job conditionally on a Linux system. We demonstrated how to identify the condition that triggers the execution of the job, create the script that will be executed, monitor the condition using the inotifywait command, and schedule the job using crontab.

Conditional job execution can be a powerful tool for automating routine tasks on a Linux system. By using crontab in combination with other Linux tools, you can create sophisticated automation workflows that respond to specific events and conditions. With a little creativity and experimentation, you can unlock the full potential of crontab and take your Linux automation to the next level.

Updated on: 23-Jun-2023

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements