Scheduling Jobs with Cron

July 5, 2016
Category: TIL
Tags: Infrastructure

Cron is a time-based job scheduler in Linux and Unix.

Basic usage

Read the manual:

$ man crontab

Load your personal crontab (cron table) file:

$ crontab -e

View your personal crontab:

$ crontab -l

Syntax:

min hour day of month month day of week command
* * * * * command
0 - 59 0 - 23 1 - 31 1 - 12 0 - 6 (0 to 6 are Sunday to Saturday) shell command you want to run at that time

Intervals:

  • */N is the syntax for an interval
  • You can use commas if the interval is irregular

Time Syntax Examples

Example Explanation
0 9 * * 1-5 Run Monday through Friday at 9am server time
0 15 * * * Run every day at 3pm server time
30 */2 * * * Run every 2 hours, on the half hour
0 0 1 1 * Run once a year at midnight on January 1
0 3,7,12,18 * * * Run daily at 3am, 7am, noon, and 6pm

Full example

Download a JSON file from Quandl and overwrite GOLD.json with it Monday through Friday at 5pm server time:

0 17 * * 1-5 wget -O "/path/to/quandl_data/GOLD.json" "https://www.quandl.com/api/v3/datasets/LBMA/GOLD.json"

Things to look out for

  • Surround anything with possible odd characters or spaces with quotes: URLs, local file paths, etc. This will keep you from getting errors.
  • Use a full file path from root instead of ~/ - Tildes aren’t interpreted the same way as on the command line
  • Times are always in server time. If you don’t know what time it is on the server, run: $ date

Thanks goes out to Eric Davis for helping me out with this!

Find this post useful?

Buy me a coffeeBuy me a coffee