仅在脚本未运行时运行Cron

时间:2015-03-12 18:43:19

标签: php cron

我有一个PHP脚本,一旦运行,它会检查数据库,然后运行一些URL的循环(使用CURL来抓取站点)。我希望这个脚本一天24小时运行。我目前每10分钟使用一次cPanel的cron,但问题是,有时脚本需要10分钟以上,而cron会再次尝试打开,这会造成很大的冲突。

我想要的是,某种PHP服务或cron脚本只有在未运行时才能运行脚本。

1 个答案:

答案 0 :(得分:1)

您可以使用数据库字段来控制抓取间隔并指定抓取状态(如“活动”,“完成”等),您也可以使用锁定文件,如下所示:

<pre>
// define name for lock
$lock_name = "/location/on/server/imworking.loc";

// exit script if lock file exists
if(  is_file( $lock_name  ) )  exit ( 'Lock file exists, lets exit here! );

// create new lock file before doing your things
$lock_file = fopen( $lock_name, "w" );
fwrite($lock_file , "working"); //this isn't really needed..
fclose($lock_file);


// do your stuff here, you can use try / catch statements as
// errors may prevent deleting lock file and so starting script again

//your stuff finished so let's remove lock file
unlink('/location/on/server/imworking.loc');
</pre>