Automating task in Linux with crontab

Automating task in Linux with crontab

Schedule and automate your jobs with crontab

Introduction

Crontab is a used to run scheduled tasks at the time scheduled. Common tasks like backing up files and synchronization of process or any other process can be scheduled to run at a regular time interval using crontab. The crontab uses a daemon called cron daemon which runs all the time and run the process specified at specified time. The config files and basic syntax can be found in /etc/crontab folder. You will need administrative privilege to view this file and don't modify this file.

Usage

You can schedule a job using crontab by following the steps which goes as follows, open the file where you can schedule the job.

crontab -e -u <user>

The -u option is used to edit other user crontab, you can leave the -u option if you are editing your own crontab. Then you can find a file like this,

cron.png

As we see, the job scheduled is for every week at 5.am. It backups the files. We can add new tasks using the following format,

*    *    *   *    *  Command_to_execute
|    |    |    |   |       
|    |    |    |    Day of the Week ( 0 - 6 ) ( Sunday = 0 )
|    |    |    |
|    |    |    Month ( 1 - 12 )
|    |    |
|    |    Day of Month ( 1 - 31 )
|    |
|    Hour ( 0 - 23 )
|
Min ( 0 - 59 )

ccc.webp

listing tasks

The tasks that are scheduled at the moment can be viewed by the following command,

crontab -l

The tasks scheduled can be deleted by using the following command,

crontab -i -r

The -i the option will ask for confirmation from the user before deleting the user’s crontab. If -i is not specified the crontab will be deleted immeditely.

new tasks

For examples let's create a task at 7 AM and 5 PM daily.

0 7,17 * * *  /scripts/script.sh

The 0 represent minutes , 7 and 17 represent hours and * represent match all values. The scripts/script.sh implies that the script we want to run is named script.sh in scripts folder.

The crontab provides many options to specify time

  • * -> match all values
  • , -> used to specify multiple values
  • - -> used to specify range
  • / -> used to represent steps

Let us consider another job which perform a action every five minutes,

*/5* * * * *  /scripts/script.sh

Conclusion

Try this commands in crontab to understand them fully and refer for more references here

Did you find this article valuable?

Support hari's blog by becoming a sponsor. Any amount is appreciated!