Cron
Cron is a tool that schedules repeating jobs to run automatically on unix systems.
There are many different implementations, each with some of their own quirks.
If you are looking to run a one-off job, see at.
Locations
/etc/crontab
system crontab /etc/cron.d/*
modular system crontabs /usr/local/etc/cron.d/*
third party crontabs /var/cron/tabs/${USER}
user crontabs /var/log/cron
system crontab log
Install
Archlinux
sudo pacman -S cronie sudo systemctl enable cronieFreeBSD
cron is installed/running by default.
Usage
crontab -l # list current user's crontab crontab -e # edit crontab (is validated before save)To test crontab, I generally just run
crontab -l > tmp.sh
, strip the crontab prefix, and run it.
Syntax
NOTE:
make no assumptions about environment variables within your crontab. I always either set the PATH, or I'm explicit with all paths
Each rule is non-exclusive. A command is run when all rules are matched:
- A * indicates that condition should be ignored (can be all).
- A , indicates that multiple conditions can match it.
- A */n indicates to repeat the every n interval.
# ===================== # Environment Variables # ===================== PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin # ==== # jobs # ==== # minute hour day_of_month month day_of_week <command> # 0-59 0-23 1-31 1-12 0-6 (0=sunday) <command> * 9-12,23 * * * <command> # Every day, every hour between 9-12, and at 23hr run <command> 0 */4 * * * <command> # Every day, every 4 hours, run <command> * */4 * * * <command> # Every day, every 4 hours, within that hour, every minute, run <command> */5 * * * * <command> # Every day, every 5 minutes run <command>
Tips
Environment
Cron paths should be explicit. For example, this is FreeBSD's cron environment.
PWD=/home/$USERRedirect STDOUT/STDERR
# by default cron may use 'sh' rather than 'bash/zsh' (which does not support '&>>') * * * * * command 2>&1 >> /var/log/my.logTest Cron Line
# add to crontab * * * * * /usr/bin/env > /home/username/cron-env#!/bin/sh # run-as-cron [envfile] [command] . "$1" exec /usr/bin/env -i "$SHELL" -c ". $1; $2"./run-as-cron ~/cron-env 'cron line command'Cron and Vim
The default behaviour for vim is to write to a separate file, then copy that file overtop of the file being edited on write. Depending on the cron you have installed, this may not be allowed.
This can be fixed with the setting:au FileType crontab setlocal bkc=yes