cron and crontabs on Amazon Linux AMI

Updated 20-Sep-2023

Two words time-based automation: cron and crontabs (and other apps such as anacron) are needed for so many things on a server. Here is how to use cron and crontabs on Amazon Linux AMI.

Install crontabs

This will in addition install several dependencies, including cron.

yum -y install crontabs
chkconfig crond on
service crond start
service crond status

Edit the crontabs

Remember to do this with su or root, otherwise there might be access issues with the actual items to run. vi is the default editor, but I like nano better, so:

export VISUAL=nano; crontab -e

Crontab syntax

Essentially there are numbers or asterisks for when things are run. From left to right: - Minute (0-59) - Hour of day (0-23) - Day of month (1-31) - Month (1-12) - Day of week (0-6, 0 = Sunday) An asterisk counts for every possible value, which means: > * * * * * = every minute > 0 1 * * * = 01:00 every day > 0 18 * * 0 = Every Sunday at 18:00 (6pm)

Crontab execution

Crontab executes from home directory of the user. It is best to use full paths for the location of scripts and the like

Example MySQL watchdog script

Crontab entry:

* * * * * /usr/local/bin/rsmy >> /var/log/mysqld.log

Script entry:

UP=$(/etc/init.d/mysqld status | grep running | grep -v not | wc -l);
if [ "$UP" -ne 1 ];
    echo "$(date) - MySQL is down - restarting now";
    /sbin/service mysqld start
    echo "$(date) - MySQL is running";
    /usr/bin/free -m