我如何确保我只有一个通过Apache运行的PHP脚本实例?

我有一个index.php脚本,我在Google Code站点上用作提交后的URL。 这个脚本克隆一个目录并build立一个可能需要一些工作的项目。 我想避免让这个脚本并行运行多次。

有一种机制,我可以用来避免执行该脚本,如果另一个已经在会议?

您可以使用LOCK_EX flock来获得对文件的独占锁定。

例如:

 <?php $fp = fopen('/tmp/php-commit.lock', 'r+'); if (!flock($fp, LOCK_EX | LOCK_NB)) { exit; } // ... do stuff fclose($fp); ?> 

对于5.3.2之后的PHP版本,您需要使用flock($ fp,LOCK_UN)手动释放锁定;

只有保存正在运行的脚本的状态,并检查脚本何时启动,如果其他脚本当前处于活动状态。

例如,要保存脚本是否正在运行,可以这样做:

 $state = file_get_contents('state.txt'); if (!$state) { file_put_contents('state.txt', 'RUNNING, started at '.time()); // Do your stuff here... // When your stuff is finished, empty file file_put_contents('state.txt', ''); } 

运行需要多长时间?

可以使用memcache

 <?php $m = new Memcache(); // check the constructor call if( $m->get( 'job_running' ) ) exit; else $m->set( 'job_running', true ); //index code here //at the end of the script $m->delete( 'job_running' ); ?> 

如果任务失败,则需要从memcache中清除。 羊群也是一个不错的选择…实际上可能更好。