PHP - 防止在Cron中的冲突 - 文件锁安全? [英] PHP - Preventing collision in Cron - File lock safe?

查看:160
本文介绍了PHP - 防止在Cron中的冲突 - 文件锁安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个安全的方法来防止cron工作冲突(即,如果另一个实例已经运行,则阻止它运行)。



a href =http://www.shepardtone.com/blog/2010/11/18/preventing-cron-job-collision/>我发现推荐的选项使用文件上的锁。 / p>

这真的是一个安全的选择吗?如果脚本死亡会发生什么?

解决方案

是否还有其他方法?



$ b <

此示例是在 http://php.net/flock 下进行的,更改了一点,这是一个正确的方式做你想要的:

  $ fp = fopen(/ tmp / lock.txt,w + ); 

if(flock($ fp,LOCK_EX | LOCK_NB)){//做独占锁
//做工作

flock($ fp,LOCK_UN ); //释放锁
} else {
echo无法获取锁!
}

fclose($ fp);

学分:




I'm trying to find a safe way to prevent a cron job collision (ie. prevent it from running if another instance is already running).

Some options I've found recommend using a lock on a file.

Is that really a safe option? What would happen if the script dies for example? Will the lock remain?

Are there other ways of doing this?

解决方案

This sample was taken at http://php.net/flock and changed a little and this is a correct way to do what you want:

$fp = fopen("/tmp/lock.txt", "w+");

if (flock($fp, LOCK_EX | LOCK_NB)) { // do an exclusive lock
    // do the work

    flock($fp, LOCK_UN); // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

Credits:

这篇关于PHP - 防止在Cron中的冲突 - 文件锁安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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