Skip to content

Refactoring Cron Parser #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 79 additions & 52 deletions CronExpression.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace dee\console;

use Yii;
use yii\base\Object;
use yii\base\BaseObject;

/**
* Description of CronExpression
Expand All @@ -14,8 +14,9 @@
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
* @since 1.0
*/
class CronExpression extends Object
class CronExpression extends BaseObject
{
const PART_REGEX = '/^(\*|\d+(-\d+)?)(\/\d+)?$/';
/**
*
* @var int
Expand Down Expand Up @@ -117,69 +118,95 @@ public function isDue($expression)
if ($expression === true) {
return true;
}
try {
$parts = explode(' ', $expression);
foreach ($parts as $i => $part) {
$valid = false;
foreach (explode(',', $part) as $p) {
if ($this->test($i, $p)) {
$valid = true;
break;
}
}
if (!$valid) {
return false;
$parts = preg_split('/\s+/', trim($expression));
if (count($parts) !== 5) {
return false;
}
foreach ($parts as $i => $part) {
$valid = false;
foreach (explode(',', $part) as $p) {
$valid = $i == 4 ? $this->testWeek($p, $this->_parts[$i]) : $this->test($p, $this->_parts[$i]);
if ($valid) {
break;
}
}
return true;
} catch (\Exception $exc) {
Yii::error($exc->getMessage(), __METHOD__);
return false;
if (!$valid) {
return false;
}
}
return true;
}

/**
* @param int $i
* @param string $part
* @param int $current
* @return boolean
*/
private function test($i, $part)
protected function test($part, $current)
{
if (!isset($this->_parts[$i])) {
return false;
}
$current = $this->_parts[$i];
if ($part === '*' || $part == $current) {
return true;
}
if (strpos($part, '/') === false) {
$range = explode('-', $part, 2);
if (empty($range[1])) {
return false;
}
$valid = $current >= $range[0] && $current <= $range[1];
if ($valid) {
return true;
if (preg_match(self::PART_REGEX, $part, $matches)) {
if (empty($matches[3])) { // without step
if (empty($matches[2])) { // without range
return $matches[1] == '*' || $matches[1] == $current;
} else {
list($from, $to) = explode('-', $matches[1]);
return $from <= $current && $current <= $to;
}
} else { // with step
$step = int_val(substr($matches[3], 1));
if ($step == 0) {
return false;
}
if (empty($matches[2])) { // without range
$from = $matches[1] == '*' ? 0 : $matches[1];
return $current >= $from && ($current - $from) % $step == 0;
} else {
list($from, $to) = explode('-', $matches[1]);
return $from <= $current && $current <= $to && ($current - $from) % $step == 0;
}
}
return $i == 4 && $current == 0 && 7 >= $range[0] && 7 <= $range[1];
}
return false;
}

// step time
$parts = explode('/', $part, 2);
if (empty($parts[1]) || (int) $parts[1] <= 0) {
return false;
}
list($part, $step) = $parts;
if ($part === '*' || $part == '0') {
return (int) ($current % $step) == 0;
}
$range = explode('-', $part, 2);
$offset = $range[0];
$to = isset($range[1]) ? $range[1] : $current;
$valid = $current >= $offset && $current <= $to && (int) (($current - $offset) % $step) == 0;
if ($valid) {
return true;
/**
* @param string $part
* @param int $current
* @return boolean
*/
protected function testWeek($part, $current)
{
if (preg_match(self::PART_REGEX, $part, $matches)) {
if (empty($matches[3])) { // without step
if (empty($matches[2])) { // without range
return $matches[1] == '*' || $matches[1] == $current || ($matches[1] == 7 && $current == 0);
} else {
list($from, $to) = explode('-', $matches[1]);
if ($to < $from) {
$to += 7;
}
return ($from <= $current && $current <= $to) ||
($from <= ($current + 7) && ($current + 7) <= $to);
}
} else { // with step
$step = int_val(substr($matches[3], 1));
if ($step == 0) {
return false;
}
if (empty($matches[2])) { // without range
$from = $matches[1] == '*' ? 0 : $matches[1];
return ($current >= $from && ($current - $from) % $step == 0) ||
($current == 0 && 7 >= $from && (7 - $from) % $step == 0);
} else {
list($from, $to) = explode('-', $matches[1]);
if ($to < $from) {
$to += 7;
}
return ($from <= $current && $current <= $to && ($current - $from) % $step == 0) ||
($from <= $current + 7 && $current + 7 <= $to && ($current + 7 - $from) % $step == 0);
}
}
}
return $i == 4 && $current == 0 && 7 >= $offset && 7 <= $to && (int) ((7 - $offset) % $step) == 0;
return false;
}
}
31 changes: 30 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,33 @@ We can `down` or `redo` only `m160201_050020_create_table_purchase`. Use `migrat
```
./yii migrate -e=160201_050030,140527_084418
./yii migrate/down all -e=m140506_102106_rbac_init
```
```


Cron Job
---------

```php
// console config

[
...
'controllerMap' => [
'cron' => [
'class' => 'dee\console\SchedulerController',
'commands' => [
'hello' => '0 0/3 * * *',
[
'command' => ['migrate/up', '-interaction=0'],
'cron' => '@daily',
]
]
]
]
]
```

Then add `cron` command to your system crontab
```sh
* * * * * cd /path/to/your/app && /usr/bin/php yii cron
```
23 changes: 17 additions & 6 deletions SchedulerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ class SchedulerController extends Controller
* @var array
* ```php
* [
* 'migrate/up --interactive=0' => '@daily',
* 'migrate/up' => '@daily',
* [
* 'command' => ['migrate', '-i'],
* 'cron' => '@daily',
* ],
* ]
* ```
*/
Expand Down Expand Up @@ -59,12 +63,19 @@ public function actionIndex($debug = false)
$routes = [];
foreach ($this->commands as $route => $expression) {
if (is_int($route)) {
$route = $expression;
$expression = true;
if (is_array($expression)) {
$route = $expression['command'];
$expression = empty($expression['cron']) ? '@hourly' : $expression['cron'];
} else {
$route = $expression;
$expression = '@hourly';
}
}
if ($cron->isDue($expression)) {
$routes[] = $route;
$command = PHP_BINARY . " $scriptFile $route 2>&1 >>$log";
if ($expression === true || $cron->isDue($expression)) {
$route = (array) $route;
$routes[] = implode(' ', $route);
$command = array_merge([PHP_BINARY, $scriptFile], $route);
$command = implode(" ", array_map('escapeshellarg', $command)) . " 2>&1 >>$log";
$process = new Process($command, $cwd, null, null, $this->timeout);
if ($this->asynchron) {
$process->start();
Expand Down