dongmanzui8486 2014-05-31 14:10
浏览 53
已采纳

不要运行一个cron php任务,直到最后一个完成

I have a php-cli script that is run by cron every 5 minutes. Because this interval is short, multiple processes are run at the same time. That's not what I want, since this script has to write inside a text file a numeric id that is incremented each time. It happens that writers are writing at the same time on this text file, and the value written is incorrect.

I have tried to use php's flock function to block writing in the file, when another process is writing on it but it doesnt work.

$fw = fopen($path, 'r+');
if (flock($fw, LOCK_EX)) {
    ftruncate($fw, 0);
    fwrite($fw, $latestid);
    fflush($fw);
    flock($fw, LOCK_UN);
}
fclose($fw);

So I suppose that the solution to this is create a bash script that verifies if there is an instance of this php script that is running, if so it should wait until it finished. But I dont know how to do it, any ideas?

  • 写回答

5条回答 默认 最新

  • doushichi3678 2014-05-31 15:56
    关注

    The solution I'm using with a bash script is this:

    exec 9>/path/to/lock/file
    if ! flock -n 9  ; then
        echo "another instance is running";
        exit 1
    fi
    # this now runs under the lock until 9 is closed (it will be closed automatically when the script ends)  
    

    A file descriptor 9> is created in /var/lock/file, and flock will exit a new process that's trying to run, unless there is no other instance of the script that is running.

    How can I ensure that only one instance of a script is running at a time (mutual exclusion)?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?