简体   繁体   English

仅在脚本未运行时运行Cron

[英]Run Cron only if the script is not running

I have a PHP script which once its run, it check the database and then run a loop of some URLs (using CURL to scrape sites). 我有一个PHP脚本,该脚本一旦运行,它将检查数据库,然后运行一些URL循环(使用CURL刮擦站点)。 I want this script to be running 24 hours a day. 我希望该脚本每天24小时运行。 I am currently using cPanel's cron for every 10 minutes, but the problem is, sometimes the script takes more than 10 minutes and cron tries to open again which makes a big conflict. 我目前每10分钟使用cPanel的cron,但问题是,有时脚本需要花费10多分钟,而cron试图再次打开,这造成了很大的冲突。

What I want is, some sort of PHP service or a cron script to run the script only if its not running. 我想要的是某种PHP服务或cron脚本,以仅在脚本未运行时运行该脚本。

You can use database fields to control scraping intervals and assign scraping status (like 'active', 'done' etc.), you can as well use a lock file, something like that: 您可以使用数据库字段来控制抓取时间间隔并分配抓取状态(例如“活动”,“完成”等),还可以使用锁定文件,如下所示:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM