Mubarak Zeb
Mubarak Zeb

Reputation: 13

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). I want this script to be running 24 hours a day. 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.

What I want is, some sort of PHP service or a cron script to run the script only if its not running.

Upvotes: 0

Views: 360

Answers (1)

Tom St
Tom St

Reputation: 911

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>

Upvotes: 1

Related Questions