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


How to check if php script is already running

如何创建不可阻挡的循环,如果它已经在运行,请不要再次运行它,我假设如果脚本运行它会更新数据库中的最后一个 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();
}
?> 

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

PHP PCNTL 就是你所需要的!你可以用它分叉PHP进程。

                 while(true) { // Infinite
                     $pid = pcntl_fork();
                        switch (pcntl_fork($pid)) {
                                case -1:
                                        die('Fork failed');
                                        break;
                                case 0: // Child
                                        processing();
                                        exit(0);
                                        break;
                                default: // Parent
                                        pcntl_waitpid($pid, $status);
                                        break;
                        }
        }