Using Crontab OS X Yosemite
Cron jobs are great for scheduling scripts to run periodically. They can be used to send out a daily email, remind yourself to take out the trash or do daily housekeeping chores like delete temp files. I needed to run a custom Django-admin script to update the models in my app. Here is how I did it.
First of all there are two methods described in the Apple Developer Guide that provide for scheduled background tasks. Launchd and crontab. I would recommend reading the docs to gain a deeper understanding of launchd and why it’s prefered. I choose to use Crontab since it is the simplest option.
OS X 10.10’s implementation of crontab has only a few parameters:
- Crontab -l. Lists all active cron jobs.
- Crontab -r. Removes all active cron jobs.
- Crontab -e. Opens up crontab file for editing.
- Crontab -u [user]. Assigns the cron job to a specific user.
In terminal you can check to see if any cron jobs exist by entering crontab -l. It doesn’t matter what directory you’re currently in. To create a cron job simply enter crontab -e and the crontab will open in a command line editor. In my case it is Vim. If you’re not familiar with Vim check out this cheat sheet.
Below I’ve listed the two lines in my crontab. In this example the jobs run at 8:11 and 8:13 every morning. The * * * represent day, month and day of week, respectively. For specific instruction for setting time read the Wikipedia entry. The command to run is followed by the time/frequency entry.
So how do you know if the job completed? In my script I have ‘print’ statement to indicate if the model was updated. When the cron job executes the print output is automatically routed to a message and sent to a file with this path /var/mail/’username’. When a new message arrives you will be notified upon opening terminal or after hitting enter in the command line.
To read the message use ‘cat’ followed by the path to your message file. Here is my latest message. The body of the message contains what normally would print out on the CLI or in Python interpreter.
If you don’t delete the message file, messages will accumulate. If you only want to keep this file for 30 days, simply create a cron job to delete the message file every 30 days.