Scheduling Jobs with Crontab and At

Scheduling Jobs with Crontab and At

I’ve been a long time crontab user, but recently it was requested that I use at for scheduling some weekly jobs. at was preferred because it is a queue, so you can add jobs that will run at a specified time, then the queue can be listed and modified. With crontab you have to create a schedule once, then if you want to change things you have to comment out jobs or modify the crontab, then change things back when your schedule returns to normal.

The problem with at is that every time something runs it needs to be scheduled, instead of the “run every tuesday at 1pm” that you can do with crontab. So I needed to combine the automation of crontab with the flexibility of at, and this is what I came up with.

For example, suppose I need to run every Tuesday at 10am. runs a report on data that was supposed to be entered on Monday, and creates a report that needs to be ready Tuesday morning. This is starting to sound ridiculous but bear with me.

To handle automatic scheduling, I use a perl script:

my $weekday = (localtime)[6];
if ($weekday == 2) { # if it's Tuesday
  print "Scheduling at 10am todayn";
  `at -f "10am today"`;

Now I add a crontab entry to run my perl script at 6am everyday. On Tuesday morning, the condition will be met and will be added to my at queue. I will receive an email saying as much, so I’ll know that it’s ready to run.

Here’s how this is useful. Suppose we had a long weekend, and the office was closed on Monday. Tuesday morning I’ll receive the email, and I’ll know that I need to reschedule it for Wednesday. I can remove the existing job from my at queue and add it for tomorrow instead. I don’t need to change any of the scripts or schedules, I just need to modify one job.

No, it’s not an earth-shattering discovery, but I think it’s a handy way to utilize crontab and at in the same system. The application I’m using this for is very susceptible to scheduling changes, and this seems like a good mix of automation and manual oversight.