Enable/Disable tasks in Crontab by Bash/Shell

瘦欲@ 提交于 2019-12-04 08:47:43

问题


Is there a way to enable and disable Crontab tasks using Bash/Shell?

So when the user starts Server 1, it will enable the Server 1 Crontab line and so on. And when the user stops Server 1, the Server 1 Crontab line get disabled (#). Is this possible and how?

Thanks in advance

*/1 * * * * Server 1 check
*/1 * * * * Server 2 check
*/1 * * * * Server 3 check

回答1:


SERVERNUM=$1

To enable:

crontab -l | sed "/^#.*Server $SERVERNUM check/s/^#//" | crontab -

To disable:

crontab -l | sed "/^[^#].*Server $SERVERNUM check/s/^/#/" | crontab -

Transcript:

barmar@dev$ crontab -l
*/1 * * * * Server 1 check
*/1 * * * * Server 2 check
*/1 * * * * Server 3 check
barmar@dev$ crontab -l | sed '/^[^#].*Server 1 check/s/^/#/' | crontab -
barmar@dev$ crontab -l
#*/1 * * * * Server 1 check
*/1 * * * * Server 2 check
*/1 * * * * Server 3 check
barmar@dev$ crontab -l | sed '/^#.*Server 1 check/s/^#//' | crontab -
barmar@dev$ crontab -l
*/1 * * * * Server 1 check
*/1 * * * * Server 2 check
*/1 * * * * Server 3 check



回答2:


I suggest you add your cron jobs to /etc/cron.d for every server one script. Then let the cron script scan for some marker file if the cron job should be executed.




回答3:


this is a variant, I use a cronjob that loads it self every night. I just edit a file and it gets reloaded at 10pm everynight. You could make the reload happen more often. I keep a directory of files for each of nodes. The trick is make sure that nobody comments out the reload line.

0 22 * * * crontab /home/ME/cron_files/NODE



回答4:


As a quick and dirty fix, you can enable or disable the execute permission of the appropriate cron script.

E.g. if you like to prevent locate from automatically updating its database (which can be I/O consuming):

cd /etc/cron.daily

sudo chmod a-x locate

This may be against the cron framework, but it is quickly applied and it works in case of immediate needs.



来源:https://stackoverflow.com/questions/14011065/enable-disable-tasks-in-crontab-by-bash-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!