Cronjob

By xngo on June 30, 2019

Cron is a time-based job scheduler. It is used to schedule jobs to run periodically at specifc dates and times. Cron runs every minute and it will inspect the crontab file to see whether a job need to be run.

In order to schedule your job, you simply set your instructions in the crontab file and then Cron will take care of running them. Crontab has the following format:

<MIN> <HR> <DOM> <MON> <DOW> <COMMAND>
  • <MIN>: It is the minute field which can take values from 0 to 59.
  • <HR>: It is the hour field which can take values from 0 to 23.
  • <DOM>: It is the day of month field which can take values from 1 to 31.
  • <MON>: It is the month field which can take values from 1 to 12.
  • <DOW>: It is the day of week field which can take values from 0 to 6(Sunday to Saturday)
  • <COMMAND>: Comand to be executed.

Note: Every single field, except for <COMMAND>, can be set to *. It means that the command will be executed for every single value of the field specified.

For example, if I want to run script.sh every day at 1:27 AM. The crontab format should be 27 1 * * * script.sh.

To put your job instructions in the Crontab file, you can either save 27 1 * * * script.sh into a file(e.g. myfile.txt) and then run crontab myfile.txt or run echo "27 1 * * * script.sh" | crontab.

Here are some periodicities that I frequently used as references.

# Run script.sh on December 31 at 23:59 
59 23 31 12 *   /absolute/path/script.sh
 
# Run script.sh using Bash.
59 23 31  12 *  /bin/bash /absolute/path/script.sh
 
# Run Bash commmand.
59 23 31  12 *   /bin/bash -c "(source /root/.bashrc; /a/myscript.sh 'arg1')"
 
# Use comma to specify specific time interval(e.g. Run at 4AM and 4PM)
0 4,16 * * *    /a/script.sh
 
# Run script.sh every 15 minutes.
*/15 * * * *    /a/script.sh
 
# Run script.sh every 15 minutes from 3AM to 5:45AM and 9PM to 11:45PM
*/15 3-5,21-23 * * *    /a/script.sh
 
# Range from 11PM to 12AM(23-00) will not work. Use 23.
* 23 * * *  /a/script.sh
 
# Escape % by adding \%.
*/5 * * * * touch /tmp/file_$(date +'\%Y-\%m-\%d_\%0k.\%M.\%S')

List current jobs

crontab -l

Append job to crontab

(crontab -l ; echo "0 4 * * * /a/script.sh")| crontab -

Log

# Log stout & sterr to myjob.log.
* * * * * /a/myjob.sh >> /var/log/myjob.log 2>&1
 
# Check what is cron job is being executed.
grep CRON /var/log/syslog

Tips

  • For your command, if you use a script file, then always use absolute path. Otherwise, it can't file your script and failed.
  • In your script file, always set the shell environment you want the script to run, e.g. #/bin/bash.
  • In your script, source your ~/.bashrc to bring all your environment variables in. Otherwise, all environment PATH are not loaded.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.