如果条件为真,则让 cron 作业休眠 5 分钟

Rav*_*nth 6 linux shell

我有一个脚本设置为每分钟运行一次。但是在我们提到的脚本中,如果条件为真,脚本必须休眠 5 分钟。这会如何影响 crontab?脚本会处于睡眠模式 5 分钟,还是会按照它在 crontab 中设置的每 1 分钟再次运行?

cha*_*aos 19

你有两个选择来获得这个。通常,cron 与作业的前一个实例是否仍在运行无关。

选项1:

在脚本的开头写一个锁定文件,完成后将其删除。然后在脚本开始时检查文件是否存在,如果存在,脚本结束而不做任何事情。例如,这可能看起来像这样:

# if the file exists (`-e`) end the script:
[ -e "/var/lock/myscript.pid" ] && exit

# if not create the file:
touch /var/lock/myscript.pid

...
# do whatever the script does.
# if condition
sleep 300 # wait 5 min
...

# remove the file when the script finishes:
rm /var/lock/myscript.pid
Run Code Online (Sandbox Code Playgroud)

选项 2:

还有一个实用程序。它被称为run-one。从联机帮助页:

run-one - 在某个命令和一组独特的参数中一次只运行一个实例(对 cronjobs 很有用,例如)

然后 cronjob 可能看起来像这样:

* * * * *   /usr/bin/run-one /path/to/myscript
Run Code Online (Sandbox Code Playgroud)