18 February 2013

multiple cron job using same file

Hi guys, Today I am posting something about cron. 1 year back, I was getting some trouble in my project in scheduling cron. I had lots of task to be managed by cron, for that I was making multiple files. But after some research I managed those task by a single file.

If your cron job accomplish similar tasks or requires the same libraries you will have to include the same files over and over to all your cronjobs ... or use this solution.

Let say you have these cron jobs:
  
0 1 * * * /etc/lib/php -q /home/user/cron/cron1.php
15 1 * * * /etc/lib/php -q /home/user/cron/cron2.php
30 1 * * * /etc/lib/php -q /home/user/cron/cron3.php
0 2 * * * /etc/lib/php -q /home/user/cron/cron4.php
    
 

And each of these cron jobs perform different tasks but use the same libraries like phpmailer, pdf creator, geoip, payment verification etc...

The idea is simple, separate tasks or commands using parameters:
  
0 1 * * * /etc/lib/php -q /home/user/cron/cron1.php --task=task1
15 1 * * * /etc/lib/php -q /home/user/cron/cron2.php --task=task2 --filter=cron3
30 1 * * * /etc/lib/php -q /home/user/cron/cron3.php --task=task3 --param=cron3
0 2 * * * /etc/lib/php -q /home/user/cron/cron4.php --task=task4
    
 

In order to accomplish this, the main cronjob file will required the following PHP code:
  
function getArguments() {
  $argument = array();
  for($i = 1; $i < $_SERVER['argc']; ++$i) {
    if(preg_match('#--([^=]+)=(.*)#', $_SERVER['argv'][$i], $reg)) {
      $argument[$reg[1]] = $reg[2];
    }
  }
  return $argument;
}

$argv = getArguments();
    
 

Then in your cron.php simply use this code to separate tasks or commands:
  
// include libraries

if($argv['task'] == 'task1') {
  // do task
}
elseif($argv['task'] == 'task2') {
  require('/path/to/cron/task2.php');
}
// etc...
    
 

No comments:

Post a Comment