Lastwish
Lastwish

Reputation: 327

How to schedule multiple CronJobs using bash without conflicting each other?

I have 4 Jobs, which run at different intervals. How can I prevent them from conflicting each other? Job 2,3,4 can only be run one at a time. Any new job invocation must wait for old completion before beginning.

0 9,11,14 * * 1-5 /bin/bash /home/userName/Desktop/Auto/job_1.sh   
0 8-17 * * 1-5 /bin/bash /home/userName/Desktop/Auto/job_2.sh
*/6 * * * * /bin/bash /home/userName/Desktop/Auto/job_3.sh
*/20 * * * * /bin/bash /home/userName/Desktop/Auto/job_4.sh

Any help is much appreciated. Thanks!

Upvotes: 0

Views: 424

Answers (1)

steveH
steveH

Reputation: 320

I would look into using flock. You have to install util-linux to get flock. It has lots of options like timeout, etc. Your crontab could look something like this:

0 9,11,14 * * 1-5 flock -x /tmp/cronjobs.lock -c '/bin/bash /home/userName/Desktop/Auto/job_1.sh'
0 8-17 * * 1-5 flock -x /tmp/cronjobs.lock -c '/bin/bash /home/userName/Desktop/Auto/job_2.sh'
*/6 * * * * flock -x /tmp/cronjobs.lock -c '/bin/bash /home/userName/Desktop/Auto/job_3.sh'
*/20 * * * * flock -x /tmp/cronjobs.lock -c '/bin/bash /home/userName/Desktop/Auto/job_4.sh'

The syntax for flock is: flock -x <lockfile> -c '<command>' The lockfile is a file that is locked on your machine. Each new command will check to see if that file is locked by a previous command. Once that previous command finishes, it releases the lock and the next command can run, taking out a new lock. Using the -w <seconds> command you can tell flock the time in seconds to wait while trying to take out a lock on the file before the command fails and does not run. For instance, the following would wait 3 minutes for previous cron job to finish. If it did not finish in that time then the command below would not run.

*/20 * * * * flock -w 180 -x /tmp/cronjobs.lock -c '/bin/bash /home/userName/Desktop/Auto/job_4.sh'

Upvotes: 1

Related Questions