php - 网页的单个实例

标签 php mysql cron

我有几个由 cron 调用的 php 脚本。 cron 作业每 20 分钟运行一次。有时脚本在几分钟内完成工作,有时需要 20 多分钟。

我想在这里防止竞争条件。我想到的一种方法是在页面运行时使用数据库设置标志,并在作业完成时删除标志。但是我真的不想用数据库。

还有其他解决办法吗?

最佳答案

(我用过的)最好的方法是将进程 ID 保存在“锁定文件”中。

function getLock() {
    //First, check to see if the script is already running
    $data = @file_get_contents('path/to/process.pid');
    if ($data && posix_kill($data, 0)) {
        throw new RuntimeException(
            'Unable To Attain Lock, Another Process Is Still Running'
        );
    }
    file_put_contents('path/to/process.pid', posix_getpid());
}

基本上,它读取文件,然后尝试 posix_kill里面包含的pid。请注意,当您将 0 信号用于 posix_kill 时,它只会告诉您调用是否会成功(意味着进程正在运行)。

这样做的好处是,如果进程在没有清理锁定文件的情况下终止,它将被检测到并再次运行。

关于php - 网页的单个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3387851/

相关文章:

php - 在此服务器上找不到请求的资源。 Cloud9 IDE 上的 Laravel

php - 无法创建mysql表

java - Hibernate JPA create table type=InnoDB 问题

mysql - 如何向 Rails 中的 ActiveRecord 对象添加属性/使用 method_missing 方法?

php - 执行连接 UPDATE 查询时 mysql_query 返回 true

cron - PHP - 最后一次通话

postgresql - docker + Crontab : find container ID from service name for use in crontab

javascript - Bootstrap Modal 不随默认浏览器页面滚动条滚动

PHP:MySQL 到表

ubuntu - 不同的 Crontab?