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?
Simply change the editor to tee command:
This would check to ensure that your command doesn't already exist before adding it.
Cheers.
It's always worked well for me.
You should consider a slightly more sophisticated script that can do three things.
Append a crontab line; assuring that it didn't exist. Adding when it already exists is bad.
Remove the crontab line. Perhaps only warning if it didn't exist.
A combination of the above two features to replace the crontab line.
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, e.g.:
Filename:
/etc/cron.d/per_minute
Content:
* * * * * root /bin/sh /home/root/script.sh
Piping stdout into
crontab
didn't install the new crontab for me on macOS, so I found this solution instead, using thetee
editor in a sub shell: