Question

I am working on a scraping project, somewhere in the application I need this functionality

run a script again and again with a pause of some seconds.

I tried to use pcntl to accomplish the job. so wrote this script

/************************/
$intra_sleep=10; // we're going to set the intra process launch sleep at 10 seconds
$task_process=null; // by default this is set to null -- do nothing
$loop_limit=0; // this is the number of times the loop shoul run -- if set to -1 look infinite number of times

if (isset($argv[1])) $task_process=$argv[1];
if (isset($argv[2])) $intra_sleep=$argv[2];
if (isset($argv[3])) $loop_limit=$argv[3];


for ($loop_count=0; $loop_limit==-1 ? true : $loop_count< $loop_limit; $loop_count++) 
{
  $pid= pcntl_fork();

   if ($pid == -1) 
   {
    die('MASTER: could not fork');
   } 
   else if ($pid==0) 
   {
     if ($task_process) 
     { 
       echo "Sleeping for  $intra_sleep Seconds\n"; 
       sleep($intra_sleep);
       echo "Launching Child \n\n"; 
       exec($task_process); // from here process script is being launched
     } 
     else 
     {
    echo "  CLONE: no task process defined -- doing nothing " . PHP_EOL;
     }
  } 
  else 
  {
     pcntl_waitpid($pid,$status);  
  } 


}

/*********************/

I am calling this script from CLI like this way

nohup php /this/script.php "php /path/to/process.php" 10 -1

I expect that process.php will be launched again and again with 10 seconds intervals. It was doing work what I was expecting, but when I check runing processes, there were thousands processed running, launched by this script.

My requirement is very simple: a script should be launched again and again with 10 second Pause.

Was it helpful?

Solution

If you just want to repeat a PHP script every x seconds, then you could use The Fat Controller to handle all the daemonising and running of scripts for you so you can concentrate on business logicin your PHP script. It's written in C so it's very stable, no matter what you do in your PHP scripts.

It basically provides the following functionality:

  • daemonising, so you don't have to mess about with nohup)
  • multitasking, in your case not relevant so you just set concurrent processes to 1
  • repeated running, so you don't have to mess about with forking.

There's lots of functionality to handle errors in PHP scripts and erroneous long running scripts.

It's pretty easy to install and get set up and there's plenty of documentation on the website to get you started. It's worth a quick look at least to see if it will help you.

http://fat-controller.sourceforge.net/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top