Scheduled task file lock

scenes to be used

Use scheduled tasks to perform operations that need to modify the state, such as revenue distribution. When the amount of data on the website or the amount of concurrency is large, the program or database is blocked, so that the current task is not completed, the second task has already started running. At this time, the state of the data to be executed read from the database by the previous task may not have changed. The two tasks may read the list of repeated information to be executed that need to be operated, resulting in repeated assignments and other consequences.
At this time, we need to ensure that the first When one task is not finished, the second task does not start or execute. The execution of the scheduled task is controlled by the operating system, which is not easy for us to operate; the script file that we are easy to operate is the script file, which can make the script not execute

Ideas

The basic idea is to use php's own flockThe file lock function, when the scheduled task is executed, lock the file and unlock it after the end. When the next task is executed, judge whether the file is unlocked or not, skip the program execution

step

//首先建立一个文件作为脚本的替代文件,因为不能直接在文件内给当前文件加锁
//通过判断替代文件的锁定状态来决定脚本执行与否
$fp = fopen('file_lock.txt', "r");//打开文件
// 加锁
if(flock($fp, LOCK_EX)){
    //加锁成功,说明文件之前未锁定,执行操作
    ......
    //执行完毕后,解锁文件
    flock($fp,LOCK_UN);
}else{
    //加锁失败,说明文件未解锁,跳过执行操作
    echo 'no act';
}
fclose($fp);

Guess you like

Origin blog.csdn.net/u012830303/article/details/103233594