Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically create a new cron job?

Tags:

linux

unix

cron

People also ask

How do I run a cron job automatically?

Cron is a job scheduling utility present in Unix like systems. The crond daemon enables cron functionality and runs in background. The cron reads the crontab (cron tables) for running predefined scripts. By using a specific syntax, you can configure a cron job to schedule scripts or other commands to run automatically.


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


OP's solution has a bug, it might allow entries to be added twice, use below to fix.

(crontab -l ; echo "0 * * * * your_command") | sort - | uniq - | crontab -

To Add something to cron

(crontab -l ; echo "0 * * * * hupChannel.sh") 2>&1 | grep -v "no crontab" | sort | uniq | crontab -

To remove this from cron

(crontab -l ; echo "0 * * * * hupChannel.sh") 2>&1 | grep -v "no crontab" | grep -v hupChannel.sh |  sort | uniq | crontab -

hope would help someone


Most of the solutions here are for adding lines to the crontab. If you need more control, you'll want to be able to control the entire contents of the crontab.

You can use piping to do this pretty elegantly.

To completely rewrite the crontab, do

echo "2 2 2 2 2 /bin/echo foobar" |crontab -

This should be easy to combine with other answers described here like

crontab -l | <something> | tee |crontab -

Or, if you have the contents in a file, it is even simpler

cat <file> |crontab -

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


Simply change the editor to tee command:

export EDITOR="tee"
echo "0 * * * * /bin/echo 'Hello World'" | crontab -e

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, because uniq only works on adjacent lines.

CMD='wget -O - -q http://www.example.com/cron.php"'
(crontab -l ; echo "0 * * * * $CMD") | sort | uniq | crontab -

If you currently have an empty crontab, you will receive the following error to stderr:

no crontab for user

If you want to avoid this, you can add a little bit of complexity add do something like this:

(crontab -l ; echo "0 * * * * $CMD") 2>&1 | sed "s/no crontab for $(whoami)//"  | sort | uniq | crontab -