Feb 7, 2012 admin

Notes on Cron for *nix and Mac OSX.

List all cron jobs

crontab -l	

Edit cron jobs

crontab -e


In shell configuration, export these env vars.

export EDITOR=vim
export VISUAL=vim

If using MacVim, use mvim instead of vim.

env vars


Edit crontab and add env var at the top

$ crontab -e

Example of env var in crontab

# Environment variable definitions

# **WRONG!** You cannot refer to existing variables with the `$` syntax!

# **WRONG!** You cannot use the 'export' keyword!
export PATH=/usr/bin:/usr/local/bin

# Correct:

# Jobs:
# m h  dom mon dow   command
  * *  *   *   *     frobnicator

Common tasks and examples

Examples from https://orchestrate.io/blog/2014/03/31/cron-in-production-that-is-a-double-edged-sword/

 Stop email
     0 * * * * /command/to/run > /dev/null 2>&1 || true
 did it run?
 Solution: Touch a file and alert on the file’s age.
     0 * * * * /command/to/run && date > /var/run/last_successful_run
 When combined with the above issue, the command should look like this:
     0 * * * * ( /command/to/run && date > /var/run/last_successful_run ) > /dev/null 2>&1 || true
 When did THAT happen?
 Sometimes its prudent to redirect the output of the program into a file. This is useful for capturing the errors, or other such events. The problem is that this usually is paired with the inability to establish when something happened. Seeing a stack trace in the log doesn’t tell you much. For readability its often desirable to attach a time stamp to each line. Luckily you can accomplish this with bash fairly easily.
 Solution: Use a shell wrapper to attach timestamps.
 0 * * * * /command/to/run | while read line ; do echo `date` "$line" ; done > /path/to/the/log
 When combined with the above issues, the command should look like this:
 15 * * * * ( flock -w 0 200 && sleep `perl -e 'print int(rand(60))'` && nice /command/to/run && date > /var/run/last_successful_run ) 2>&1 200> /var/run/cron_job_lock | while read line ; echo `date` "$line" ; done > /path/to/the/log || true

Another easy way to run script in cron is to use cron_helper.sh

15 * * * * /usr/local/bin/cron_helper -c -n job_name -i -s -t /command/to/run


starter.sh script


if [ $(ps aux | grep node | grep -v grep | wc -l | tr -s "\n") -eq 0 ]
    export PATH=/usr/local/bin:$PATH
    export NODE_ENV=production
    NODE_ENV=production forever start --sourceDir /var/www index.js >> /var/log/nodelog.txt 2>&1

Change permission and edit crontab

sudo chmod +x /var/www/starter.sh
sudo crontab -e

Add this line to crontab

@reboot /var/www/starter.sh

Alternative to cron

python schedule

ruby clockwork

Jenkins Job Builder
recommended for deployment