Created
May 24, 2015 19:14
-
-
Save eberfreitas/795093bb4123364ef806 to your computer and use it in GitHub Desktop.
Cronjobs for Shell scripts in CakePHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use \Cron\CronExpression; | |
App::uses('AppShell', 'Console/Command'); | |
class CronShell extends AppShell { | |
protected $_tasks = []; | |
public function schelude() { | |
$this->add('*/5 * * * *', 'url_name_cleaning'); | |
$this->add('*/10 * * * *', 'campaigns'); | |
} | |
public function main() { | |
$this->out(date('Y-m-d H:i:s', time())); | |
$this->hr(); | |
$this->schelude(); | |
$this->run(); | |
} | |
public function add($expression, $task) { | |
$data = [ | |
'exp' => CronExpression::factory($expression), | |
'task' => $task | |
]; | |
$this->_tasks[] = $data; | |
} | |
public function run() { | |
$toExecute = []; | |
foreach ($this->_tasks as $task) { | |
if ($task['exp']->isDue()) { | |
$toExecute[] = $task['task']; | |
} | |
} | |
if (empty($toExecute)) { | |
$this->out('No tasks to run now! Terminating...'); | |
$this->hr(); | |
return; | |
} | |
$this->out(count($toExecute) . ' task(s) to execute!'); | |
foreach ($toExecute as $task) { | |
$this->out('- ' . $task); | |
} | |
$this->hr(); | |
$this->out('RUNNING...'); | |
foreach ($toExecute as $task) { | |
$this->dispatchShell($task); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment