Saturday, February 17, 2007

Scheduling Tasks on Ubuntu

On UNIX-based systems, task scheduling is generally done using cron. It's a system service to run commands at a time you specify. Tasks can be scheduled by adding an entry for it in /etc/crontab.

Tasks in crontab are specified in this format:
[min] [hour] [day of month] [month] [day of week] [program/command to run]
If you use * then the task will be run for the entire range of time for that field. For example, specifying * for minutes means the task will run every single minute.

So if you want to run the echo command every minute from 8am to 9am every single day of every single month, then do the following:
* 8 * * * echo 'hello'
It's not useful to do this, but it's just to show you the basics of how it works. You don't have to perform shell commands either. I use cron to run a Python script to change my wallpaper every Saturday at 8pm. Nothing earth shattering, but to each his own ;-)

Here's the cron job I specified to do this:
00 20 * * 6 python
You can even use abbreviations for the day of week (Mon, Tues, Sat, etc...) instead of numbers. I'm not sure if this works for the month field as well. I didn't try it, but there's always the man page if you're interested in knowing.

One final note: cron assumes your machine is running 24/7, so if your machine isn't powered on all the time your task may not run unless you make sure your machine is up and running when a task is supposed to run. There's another task scheduler to solve that issue called anacron, but I haven't used it so I'll refrain from embarrassing myself until I learn at least the basics of how to make it work :-P