Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/Disable tasks in Crontab by Bash/Shell

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
like image 295
user1621988 Avatar asked Dec 23 '12 12:12

user1621988


2 Answers

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
like image 164
Barmar Avatar answered Oct 02 '22 23:10

Barmar


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.

like image 22
Ortwin Angermeier Avatar answered Oct 03 '22 01:10

Ortwin Angermeier