如何在硬件故障后恢复此脚本?

Che*_*tah 1 php

我知道这有点泛,但我相信你会理解我的解释.情况如下:


以下代码每10分钟执行一次.变量"var_x"在被引用时始终被读/写到外部文本文件中.

if ( var_x != 1 )
{
   var_x = 1;
   //
   // here is where the main body of the script is.
   // it can take hours to completely execute.
   //
   var_x = 0;
}
else
{
   // exit script as it's already running.
}
Run Code Online (Sandbox Code Playgroud)

问题是:如果我模拟硬件故障(在脚本执行时执行硬重置),那么主脚本逻辑将永远不会再次执行,因为"var_x"将始终为"1".(我已经有了解决恢复点的逻辑).

谢谢.

Res*_*uum 6

您应该使用flock锁定和解锁文件:

$fp = fopen($your_file);
if (flock($fp, LOCK_EX)) { )
{
   //
   // here is where the main body of the script is.
   // it can take hours to completely execute.
   //
    flock($fp, LOCK_UN);
}
else
{
   // exit script as it's already running.
}
Run Code Online (Sandbox Code Playgroud)

编辑:

由于flock似乎无法在Windows机器上正常工作,因此您必须采用其他解决方案.从头到尾想出一个可能的解决方案:

不要将1写入var_x,而是编写通过getmypid检索的进程ID .当脚本的新实例读取文件时,它应该使用此ID查找正在运行的进程,并且该进程是PHP脚本.当然,这仍然可能出错,因为在硬件故障后有可能另一个PHP脚本获得相同的PID,因此解决方案远非最佳.


scr*_*gar 5

难道你不认为使用文件锁可以更好地解决这个问题吗?(重置发生时,文件锁也会重置)

http://php.net/flock