如何检查php脚本是否已经运行

ale*_*kow 3 php cron while-loop

如何创建不可阻挡的while循环,如果它已经运行不再运行它,我假设如果运行它的脚本将更新数据库中的最后cron时间,脚本将检查当前时间 - 40秒是否小于上一个cron时间.我所拥有的样本,但那是过度循环(一次又一次地运行)谢谢!

<?php
ignore_user_abort(1); // run script in background 
set_time_limit(0);    // set limit to 0


function processing()
{
//some function here
setting::write('cron_last_time', $time); // write cron last time to database
}

$time = current_timestamp();  // current time
$time_before = $time - 20;   //

$settings = setting::read('module_cron_email'); // Get last cron time from database ( in array )
$time_last = $settings['setting_value'];     // Last cron time get value from array



if ($time_before < $time_last) // check if time before is less than last cron time
{ 
   do{
   processing(); //run our function
   sleep(7);    // pause for 7 seconds
   continue;   // continue
   }
   while(true); // loop
}else{

echo "already running";
die();
}
?> 
Run Code Online (Sandbox Code Playgroud)

Aha*_*ius 6

启动脚本时,请检查锁定文件.如果确实存在,则退出或跳过循环.如果它不存在,请创建该文件并让它运行.

  • 标准技巧是将pid存储在锁定文件中,当存在时执行`kill -0 <pid>`并使用生成的错误代码.(要么不存在,要么属于其他uid,或者为零)如果错误为零,则进程(使用我们的uid运行的另一个进程和相同的进程号)仍然存在.通过greps ps的输出可以获得额外的信息. (2认同)
  • 为什么不拥有只代表锁的文件.循环开始时,您尝试请求锁定该文件.如果不可能,这意味着另一个脚本正在运行该过程? (2认同)