How to: Set up a cron job (For Wizards)

Today I set up a cron job for the laughs. The documentation I found was lacking. Here’s my go at it.

Cron is a unix utility written by Paul Vixie. Thanks Paul for a great utility. Cron jobs are simple to make and extremely useful. They allow you to run any kind of task you want at anytime. Say you want to run a script that emails your buddy every 30mins. That sounds perfect, and cron can do it perfectly. Let’s write a script that curls a website, and we will call it with a Cron every 59 mins.

Setting up a Cron is pretty simple. For this tutorial I’m assuming you are running on Unix. Sorry Windows folks.

The first step is to write your crontab file. This file schedules your Crons. They are formatted like so:

min hour day month week command

(*)s are wildcards. That means it will run every time it can. So if you wanted to run something every minute instead of every 59, just put a *. Or lets say you want to run it once a day at 10:30.

30 10 * * * /Users/jim/Documents/hello.py

This is an example I’ve written. It will run every 59 mins of every day, every month, every week, forever.

Screen Shot 2013-12-30 at 6.03.25 PM

Forever.

Every 59 mins it runs your command. My command is to run a shell script. You can make any command you want of course. You can make a command to email your buddy every minute of everyday forever. You should definitely write that.

Now lets set up your cron. You can find you Crons in several ways.

Terminal:      sudo -i cd /var/at/tabs

crontab:         crontab -l

Screen Shot 2013-12-30 at 6.24.10 PM

You should check these out and see what you have running, if anything, before moving forward. You probably don’t have anything running, so let’s making something.

Using you favorite editor write a txt file formatted as I’ve shown above. When do you want your cron to run? Cron checks your crontab file every minute, but I would recommend deleting this cron after you’ve played around. DON’T DO CRAZY STUFF HERE.

You should make a file like thus: ‘what.cron.txt’ or something similar. Its contents should look like thus:

30 * * * * /Users/An/myshittyhacks/myshittyscripts/emailMyBoy.frnd.py

This crontab will run every 30 mins. Or:

* * 25 12 * /Users/blackhertdeathsoul/Vitaliysmomscode/merryxmas.sh

This crontab will run every minute on December 25.

Upload your crontab file with the crontab command:    crontab path.your.cron.file

Screen Shot 2013-12-30 at 6.40.53 PM

For my cron, I wrote a shell script that calls this ruby script. I wrote a sh wrapper because I was scared. However it’s not necessary.

Screen Shot 2013-12-30 at 6.33.47 PM

Screen Shot 2013-12-30 at 6.04.17 PM

 

 

Now you’re done. They way I did this was hacky and bad, however this will get your computer to run code on a schedule! Have much fun.

Advertisements