防止Bash脚本并行运行或使用cron重叠 [英] Preventing to Bash script from running in parallel or overlap using cron

查看:288
本文介绍了防止Bash脚本并行运行或使用cron重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在cron表中有以下条目:

If i have the following entries in my cron table:

00 03 * * * /java_prog1.sh 
00 5 * * * /java_prog2.sh

第一个作业通常需要大约30分钟才能完成。第二个工作大约需要10分钟。有一些例外情况,第一个工作需要两个多小时。

The first job usually takes around 30 minutes to complete. The second job takes about 10 minutes. There are some exceptional situations where the first job takes more than two hours.

有没有办法我可以配置这两个工作,使第二个工作不启动,如果第一个工作仍在运行?

Is there a way i can configure the two jobs so that the second job does not start if the first one is still running?

我已经看到了使用 flock 等工具的几个例子,但我认为flock不适用于这里,因为我不想阻止相同的工作在同一个时间。我试图阻止另一个作业,如果前一个仍在运行。

I have seen several examples using tools like flock but i think flock does not apply here as i am not trying to prevent the same job running at the same time. I am trying to prevent another job to start if the previous one is still running.

推荐答案

只要在评论中已有的建议之上加上一些肉体。

Just putting some flesh on top of the suggestions already there in the comments.

放入 java_prog1.sh 的开头:

[ -f /var/run/java_prog1.sh.pid ] && exit
echo "$$" > /var/run/java_prog1.sh.pid

... everything else our script does ...

rm -f /var/run/java_prog1.sh.pid

然后在 java_prog2.sh

[ -f /var/run/java_prog1.sh.pid ] && exit

... the rest of your java_prog2.sh ...

或:

if [ -f /var/run/java_prog1.sh.pid ]; then
   kill -0 `cat /var/run/java_prog1.sh.pid` > /dev/null 2>&1 && exit
fi


... the rest of your java_prog2.sh ...

如果a文件(可能包含第一个脚本中的PID)存在,第一个将立即退出。第二个只有当文件存在且该文件中有PID的进程在进程表中时才会退出( kill -0 将返回0, 。

The first one will just exit immediately, if the a file (possibly and probably containing a PID from the first script) exists. The second one will exit only if the file exists and a process with a PID in in that file is in the process table (kill -0 will return 0 in case it does).

对于实际的脚本,你可能需要尝试一下。这只是给你一个粗略的想法如何可能去。

As far as the actual scripting goes, you probably have to experiment a bit. This is just to give you a rought idea how it might go.

这篇关于防止Bash脚本并行运行或使用cron重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆