Thursday 18 April 2024

Cron Utility (Unix)

cron command-line utility is a job scheduler on Unix-like operating systems. It runs as a daemon (background process).

These scheduled jobs (essentially a commands) are called cron jobs. They are repetitive tasks, scheduled to be run periodically, at certain time or interval.

Cron jobs, together with frequency and time of their execution are defined in cron table (crontab) file.
Each job is defined in its own line which has the following format:


minute (0–59)
# │ ┌───────────── hour (0–23)
# │ │ ┌───────────── day of the month (1–31)
# │ │ │ ┌───────────── month (1–12)
# │ │ │ │ ┌───────────── day of the week (0–6) (Sunday to Saturday;
# │ │ │ │ │                                   7 is also Sunday on some systems)
    *   *   *   *   *  <command to execute>


* means "every"

* * * * * = every minute, every hour, every day, every month
0 * * * * = every full hour, every day (HH:MM = *:0)
0 0 * * * = every midnight (HH:MM=0:0)
0 0 1 * * = once a month on the midnight of the first day of the month
0 10 * * * = every day at 10:00h
*/10 * * * * = every 10 minutes of every hour, every day


$ crontab
crontab: usage error: file name or - (for stdin) must be specified
Usage:
 crontab [options] file
 crontab [options]
 crontab -n [hostname]

Options:
 -u <user>  define user
 -e         edit user's crontab
 -l         list user's crontab
 -r         delete user's crontab
 -i         prompt before deleting
 -n <host>  set host in cluster to run users' crontabs
 -c         get host in cluster to run users' crontabs
 -T <file>  test a crontab file syntax
 -s         selinux context
 -V         print version and exit
 -x <mask>  enable debugging

Default operation is replace, per 1003.2


To list all cron jobs use:

$ crontab -l
* * * * * aws s3 sync ~/dir1/ s3://my-bucket/dir1 --region us-east-1 >> ~/logs/crons/s3_sync.log 2>&1
0 * * * * redis-cli -h redis-cache-group-123.cache.amazonaws.com -p 6345 flushall >> ~/logs/crons/flushRedisCache.log 2>&1
* * * * * ~/path/to/my_script1.sh >> ~/logs/crons/my_script1.sh.log 2>&1
0 0 * * * ~/path/to/my_script2.sh >> ~/logs/crons/my_script2.log 2>&1
0 0 1 * * ~/path/to/my_script3.sh >> ~/logs/crons/my_script3.log 2>&1
0 10 * * * ~/path/to/my_script4.sh >> ~/logs/crons/my_script4.log 2>&1
*/10 * * * * rsync -avhl --delete ~/path/to/source ~/path/to/dest/ >> ~/logs/crons/source_dest_rsync.log 2>&1

crontab file should not be edited with file editors but via crontab:

crontab -l



Resources:

cron - Wikipedia
Crontab – Quick Reference 
Crontab.guru - The cron schedule expression generator

No comments: