How can I programmatically create a new cron job?

2019-01-05 08:53发布

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?

标签: linux unix cron
16条回答
Summer. ? 凉城
2楼-- · 2019-01-05 09:40

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-05 09:40

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

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-05 09:43

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 -
查看更多
该账号已被封号
5楼-- · 2019-01-05 09:43

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

查看更多
可以哭但决不认输i
6楼-- · 2019-01-05 09:43

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 -
查看更多
虎瘦雄心在
7楼-- · 2019-01-05 09:46

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
查看更多
登录 后发表回答