How to schedule a job in Linux using cron

In this video, we will see how to schedule a job in Linux using cron.

cron is a system process or daemon running on a Linux system and has a responsibility to detect and execute a certain cron job in a given time period. cron job is any defined task to run in a given time period. It can be a shell script or a simple bash command. Cron job helps us automate our routine task, it can be hourly, daily, monthly, or a given interval of period.

Cron job definition/Syntax:

# .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * user-name command to be executed


crontab -a : create a new as crontab file
crontab -e: edit our crontab file or create one if it doesn’t already exist
crontab -l: show up our crontab file
crontab -r: delete our crontab file

Important Note: Before modifying any cron job, its best practice to take backup of exsting cron jobs.

Examples to schedule jobs in Linux using cron:

1. Lets verify cron system process is running or not.

sudo systemctl status cron.service

How to schedule a job in Linux using cron

2. To get list of cron jobs, run the crontab -e

crontab -e

Press Ctrl+x to quit.

3. To schedule for every minute using cron.

* * * * * /home/r2schools/processes.sh

4. Following cron job runs every day at 1.05(1 hour after 5 minutes).

05 01 * * * /home/r2schools/db_backup.sh

5. Schedule same job more than one time in a day. Then, we have to mention the time period with comma separation. Following job runs every day at morning 5AM and evening 10PM.

00 5,22 * * * /home/r2schools/db_backup.sh

6. Send the output cron job to another file.

05 01 * * * /home/r2schools/db_backup.sh >> db_backupmessages.out

7. Disable Linux job. Put the # symbol in front of the job like below highlighted.

8. To view list of cron jobs run crontab -l.

Cron job shortcuts:
Following single-word time shortcuts can be used to replace the five fields usually used to specify times. The @ character is used to identify shortcuts to cron. The list below, taken from the crontab(5) man page, shows the shortcuts with their equivalent meanings.

@reboot : Run once after reboot. @yearly : Run once a year, ie. 0 0 1 1 * @annually : Run once a year, ie. 0 0 1 1 * @monthly : Run once a month, ie. 0 0 1 * * @weekly : Run once a week, ie. 0 0 * * 0 @daily : Run once a day, ie. 0 0 * * * @hourly : Run once an hour, ie. 0 * * * *

So in this article, we have seen how to schedule a job in Linux using cron.