Linux 通过 Bash/Shell 在 Crontab 中启用/禁用任务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14011065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:06:14  来源:igfitidea点击:

Enable/Disable tasks in Crontab by Bash/Shell

linuxbashshellcrontab

提问by user1621988

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

有没有办法使用 Bash/Shell 启用和禁用 Crontab 任务?

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?

所以当用户启动 Server 1 时,它会启用 Server 1 Crontab 行等等。当用户停止服务器 1 时,服务器 1 Crontab 行被禁用 (#)。这是可能的吗?

Thanks in advance

提前致谢

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

采纳答案by Barmar

SERVERNUM=

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

回答by Ortwin Angermeier

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

我建议您/etc/cron.d为每个服务器添加一个脚本的cron 作业。如果应该执行 cron 作业,则让 cron 脚本扫描某个标记文件。

回答by kdubs

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.

这是一个变体,我使用一个每天晚上自行加载的 cronjob。我只是编辑一个文件,它会在每晚 10 点重新加载。您可以更频繁地重新加载。我为每个节点保留一个文件目录。诀窍是确保没有人注释掉重新加载行。

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

回答by Andi Hafner

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

作为一种快速而肮脏的修复,您可以启用或禁用相应 cron 脚本的执行权限。

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

例如,如果您想阻止 locate 自动更新其数据库(这可能会消耗 I/O):

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.

这可能与 cron 框架背道而驰,但它可以快速应用,并且可以在紧急需要的情况下使用。