How to schedule jobs with cron

· 2 min read linuxcronsysadmin

Cron runs commands on a schedule. Each user has their own crontab; jobs run even when you are logged out.

Edit your crontab

crontab -e

List current jobs with crontab -l. Root's table is separate: sudo crontab -e.

The five fields

* * * * *  command
│ │ │ │ │
│ │ │ │ └─ day of week (0-7, Sun=0)
│ │ │ └─── month (1-12)
│ │ └───── day of month (1-31)
│ └─────── hour (0-23)
└───────── minute (0-59)

Examples:

*/5 * * * *   every 5 minutes
0 3 * * *     daily at 03:00
0 9 * * 1-5   weekdays at 09:00
0 0 1 * *     first of every month

Shortcut strings also work: @daily, @hourly, @reboot.

Always redirect output

Cron emails output if a mailer exists; usually it does not, and errors vanish. Redirect everything:

0 3 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

Environment gotchas

Cron runs with a minimal environment: no your .bashrc, short PATH. Two fixes:

  1. Use absolute paths: /usr/bin/rsync, not rsync.
  2. Set PATH at the top of the crontab:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Test the exact command first

Cron executes via /bin/sh, not bash. Run the command in sh before trusting the entry:

sh -c '/usr/local/bin/backup.sh'

System-wide timers needing finer control (calendar events, dependencies, randomized delay) belong in systemd timers instead.