tags:

views:

1212

answers:

6

I want to be able to programatically add a new cron job, what is the best way to do this?

From my research, it seems I could dump the current crontab and then append a new one, piping that back into crontab:

(crontab -l ; echo "0 * * * * wget -O - -q http://www.example.com/cron.php") | crontab -

Is there a better way?

A: 

You could also edit the cron table text file directly, but your solution seems perfectly acceptable.

Alex Fort
I would be leery of this due to concerns of the chance of concurrent edits causing file corruption. Using the command-line crontab command should avoid that problem.
Craig S
+9  A: 

The best way if you're running as root, is to drop a file into /etc/cron.d

if you use a package manager to package your software, you can simply lay down files in that directory and they are interpreted as if they were crontabs, but with an extra field for the username (see the docs for more info)

MarkR
Just make sure the version of cron in use supports /etc/cron.d/. Most modern Linux distributions do.
sleske
+3  A: 

It's always worked well for me.

You should consider a slightly more sophisticated script that can do three things.

  1. Append a crontab line; assuring that it didn't exist. Adding when it already exists is bad.

  2. Remove the crontab line. Perhaps only warning if it didn't exist.

  3. A combination of the above two features to replace the crontab line.

S.Lott
+4  A: 

If you're planning on doing it for a run-once scenario for just wget'ing something, take a look at 'at'

Christian Witts
+1  A: 

also you can add your tasks to /etc/cron.*/

vitaly.v.ch
+1  A: 

man crontab is also useful:

CRONTAB(1)

NAME

   crontab - manipulate per-user crontabs (Dillon's Cron)

SYNOPSIS

   crontab file [-u user] - replace crontab from file

   crontab - [-u user] - replace crontab from stdin

   crontab -l [user] - list crontab for user
vitaly.v.ch