限制多个php脚本实例


Restrict multiple php script instances

我有一个脚本,运行多次,因为验证需要更长的时间,并允许脚本的多个实例。它应该每天运行一次,但昨天script_start()运行了18次,几乎在同一时间。

add_action('init', 'time_validator');
function time_validator() {
    $last = get_option( 'last_update' );        
    $interval = get_option( 'interval' );
    $slop = get_option( 'interval_slop' );
    if ( ( time() - $last ) > ( $interval + rand( 0, $slop ) ) ) {
        update_option( 'last_update', time() );
        script_start();
    }
}

听起来很混乱,您已经检测到18个脚本实例正在运行,尽管您不希望这样。你应该修复调用这些脚本实例的代码。

但是,您可以在脚本本身中实现此检查。为了确保脚本只运行一次,您应该使用flock()。我举个例子:

将其添加到每次只运行一次的代码的顶部:

// open the lock file
$fd = fopen('lock.file', 'w+');
// try to obtain an exclusive lock. If another instance is currently 
// obtaining the lock we'll just exit. (LOCK_NB makes flock not blocking)
if(!flock($fd, LOCK_EX | LOCK_NB)) {
    die('process is already running');
} 

…这和关键代码的结尾:

// release the lock
flock($fd, LOCK_UN);
// close the file
fclose($fd);

所描述的方法对竞争条件是安全的,它确实确保了临界区只运行一次。