`cron` tips

cron tips

ubuntu 18.04 hw2018 server cron

cron can be used to perform boring repetitive tasks and is heavily used by most Linux distributions.

crontab

cron uses a configuration file named crontab (manpage) which should always be edited using the crontab utility (manpage).

Every user has it’s own crontab that can be displayed using crontab -l. Users’s cron jobs will be run with the user’s permissions.

root can display a user crontab by using crontab -l -u user.

A well working cron job is expected to have no output (on sterr/stdout), otherwise the output will be sent by email to the user.

Sample crontab

Running the ./backup.sh script at 1h59, 2h59, …

crontab -l
# Edit this file to introduce tasks to be run by cron.
#
#
# m h  dom mon dow   command
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
59 1-23/2 * * * ./backup.sh > /dev/null 2>&1

crontab edition

crontab -e will run $EDITOR on your crontab.

root can edit a user crontab by using crontab -e -u user.

crontab file format

Each (non-comment) line in this file has a time description followed by a command. The file description can be 5 fields (minute hour day month weekday) or a special keyword starting by @, like @reboot.

Examples

# Every minute
* * * * * some_command

# Every 5 minutes
*/5 * * * * some_command

# Every even hour at '59
59 */2 * * * some_command

# Every odd hour at '59
59 1-23/2 * * * some_command

# at reboot
@reboot some_command

Here is a tool for explaining the time part of a command : crontab.guru.

System crontab

System crontab have got one more field, the user field:

17 *	* * *	root    cd / && run-parts --report /etc/cron.hourly

Most Linux distributions contains special directories for system periodic tasks:

Directory Description
/etc/cron.d system crontab files
/etc/cron.hourly scripts (not crontabs) to be run hourly
/etc/cron.daily scripts (not crontabs) to be run daily
/etc/cron.weekly
/etc/cron.monthly

cron problem solving

Frequency problems can be solved using crontab.guru, I know, it’s the second link to this tool, but it’s really useful.

Most execution problems while using cron are caused by cron not using the same shell (/bin/sh instead of bash), environment variables not being set (PATH, …), or the current working directory being different.

Fortunately, the real behavior can be emulated!

cron emulation

Thanks to this stackoverflow response.

  1. Get the real cron environment by adding this line to the crontab:
    30 08 * * * env > ~/cronenv # replace with some close time
    
  2. Remove the temporary cron job once the ~/cronenv file exists.
  3. Execute the command with the cron environment:
    env - `cat ~/cronenv` /bin/sh -c 'some_command'
    

Non-periodic task

at (manpage).

Example send yourself an email at noon:

echo "echo Hey, it's noon" | at noon

~~~

Question, remark, bug? Don't hesitate to contact me or report a bug.