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?
Adding to JohnZ's answer, here's the syntax to schedule as root if you are a sudoer:
You could also edit the cron table text file directly, but your solution seems perfectly acceptable.
Assuming that there is already an entry in your crontab, the following command should work relatively well. Note that the
$CMD
variable is only there for readability. Sorting before filtering duplicates is important, becauseuniq
only works on adjacent lines.If you currently have an empty crontab, you will receive the following error to stderr:
If you want to avoid this, you can add a little bit of complexity add do something like this:
Here's another one-liner way, that avoids duplicates
And here's a way to do JohnZ's answer and avoid
no crontab for user
message, or if you need to operate in aset -eu
type environment and can't have anything return a failure (in which case the2>/dev/null
part is optional):Or if you want to split things up so that they're more readable:
Or optionally remove any references to your_command (ex: if the schedule has changed, you only want it ever cron'ed once). In this case we no longer need
uniq
(added bonus, insertion order is also preserved):