我们在终端上使用下面的命令查看正在运行的 PHP 脚本:
echo 'User | ProcID | CPU | MEM | ----------------------- START | ELAPSED ---------- COMMAND';
ps aux --forest | grep php;
我希望当一个文件的多个副本同时运行时,能够收到电子邮件提醒。甚至可以自动终止早期的进程!
这发生在 cron 作业上,当一个脚本因某种原因卡住并且 cron 的下一个循环运行时间到来时,您会有一个卡住的(或不完整的、缓慢的脚本)继续运行,并且同一脚本的新实例同时运行。
您可以提供更好的 BASH 解决方案(除了修改 PHP 脚本)。
请参阅所附图片中的问题脚本示例:
\_ php -f /var/webserver/public_html/cron/scheduled_job_1.php
(process id: 3824)
答案1
确保 PHP 脚本不会同时运行两个实例的最简单方法是,在我看来,在 Bash 中编写一个小包装脚本,在运行你的确切命令之前,终止所有当前正在运行的实例。
然后,您可以在 cronjob 中执行这个包装脚本,而不是实际的 PHP 命令。
可能的包装器实现:
#!/bin/bash
my_command='php -f /var/webserver/public_html/cron/scheduled_job_1.php'
# kill processes with the exact command line as above, if any are running
if pkill -fx "$my_command" ; then
# You can do something here, which runs only if a process was killed.
# The command below would just echo a warning to the terminal (not visible as a cronjob)
echo "$(date) - WARNING: Previous instance of '$my_command' was killed."
fi
# (re)run the command
$my_command
或者是一个期望命令作为参数运行的通用包装器。
#!/bin/bash
# This script expects a command as argument(s), like e.g. "my_wrapper sleep 60"
# kill processes with the given command line, if any are running
if pkill -fx "$*" ; then
# You can do something here, which runs only if a process was killed.
# The command below would just echo a warning to the terminal (not visible as a cronjob)
echo "$(date) - WARNING: Previous instance of '$*' was killed."
fi
# (re)run the command
"$@"
如果你将它保存为/usr/local/bin/my_wrapper
,你可以像这样调用它
my_wrapper php -f /var/webserver/public_html/cron/scheduled_job_1.php