Gino Sullivan
Gino Sullivan

Reputation: 2213

multiple cronjob same php file

i have multiple cronjobs that are setup as define:

0 1 * * * php -q /home/user/cron/cron1.php
20 1 * * * php -q /home/user/cron/cron2.php
40 1 * * * php -q /home/user/cron/cron3.php
0 2 * * * php -q /home/user/cron/cron4.php

each of these cronjobs do different tasks but use the same libraries like phpmailer, pdf creator, geoip etc...

how can i combine this cronjob into one so i dont have to create 50+ files that includes the same file over and over?

thanks

Upvotes: 28

Views: 1203

Answers (1)

Book Of Zeus
Book Of Zeus

Reputation: 49867

Here's what I recommend:

0 1 * * * php -q /home/user/cron/cron.php --task=task1
20 1 * * * php -q /home/user/cron/cron.php --task=task2
40 1 * * * php -q /home/user/cron/cron.php --task=task3
#etc...

and then in your cron.php file you do:

<?php

// include libraries

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();

if($argv['task'] == 'task1') {
  // do task
}
elseif($argv['task'] == 'task2') {
  // do task
}

Upvotes: 47

Related Questions