Created
March 8, 2018 18:53
-
-
Save duhow/2b05718541fbc09255b5a247c89ce4a3 to your computer and use it in GitHub Desktop.
Cron Expression Match PHP
This file contains hidden or 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 | |
class CronExp { | |
public function match($expression, $time = NULL){ | |
if(empty($time)){ | |
$time = time() - time() % 60; // rounded to current minute | |
}elseif(is_string($time)){ | |
$time = strtotime($time); | |
} | |
$tmp = self::replaceSpecialStrings($expression); | |
if($tmp){ | |
$expression = $tmp; | |
} | |
$cronpart = self::checkValid($expression); | |
if(!$cronpart){ | |
return FALSE; | |
} | |
$procs = [ | |
['i', 0, 59], | |
['G', 0, 23], | |
['j', 0, 31], | |
['n', 1, 12], | |
['w', 0, 6] | |
]; | |
foreach($cronpart as $i => $match){ | |
foreach(explode(",", $match) as $expr){ | |
if(!self::checkCronParam( | |
$expr, $time, | |
$procs[$i][0], $procs[$i][1], $procs[$i][2]) | |
){ | |
return FALSE; | |
} | |
} | |
} | |
return TRUE; | |
} | |
private function replaceSpecialStrings($expression){ | |
$strings = [ | |
'yearly' => '0 0 1 1 *', | |
'annually' => '0 0 1 1 *', | |
'monthly' => '0 0 1 * *', | |
'weekly' => '0 0 * * 0', | |
'daily' => '0 0 * * *', | |
'midnight' => '0 0 * * *', | |
'hourly' => '0 * * * *' | |
]; | |
$expression = str_replace("@", "", $expression); | |
if(array_key_exists($expression, $strings)){ | |
return $strings[$expression]; | |
} | |
return FALSE; | |
} | |
public function checkValid($expression){ | |
$r = preg_match_all('/(([*\-\,\/\d]+)(\s+|$))/', $expression, $matches, PREG_PATTERN_ORDER); | |
// If not 5 matches, not valid cron. | |
if($r != 5){ return FALSE; } | |
return $matches[2]; | |
} | |
private function checkCronParam($expr, $time, $datesel, $mmin, $mmax){ | |
$dmatch = (int) date($datesel, $time); | |
if(in_array($expr, ['*', '*/1'])){ return TRUE; } | |
if(is_numeric($expr)){ | |
return ( (int) $expr == $dmatch ); | |
} | |
if(preg_match('/^\*\/(\d{1,2})$/', $expr, $matches)){ | |
// Data 00 always match. | |
if($dmatch === 0){ return TRUE; } | |
return ($dmatch % (int) $matches[1] == 0); | |
}elseif(preg_match('/^(\d{1,2})-(\d{1,2})$/', $expr, $matches)){ | |
$min = (int) $matches[1]; | |
$max = (int) $matches[2]; | |
// Not match if invalid. | |
if( | |
$min > $max or | |
$min < $mmin or | |
$max > $mmax | |
){ return FALSE; } | |
return ($dmatch >= $min and $dmatch <= $max); | |
} | |
// Others or not meeting get FALSE. | |
return FALSE; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A fast way of doing "cron jobs" (match time with cron syntax) using PHP.