Last active
June 9, 2022 23:35
-
-
Save goosehub/7deff7928be04ec99b4292be10b4b7b0 to your computer and use it in GitHub Desktop.
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
// http://stackoverflow.com/a/5727346/3774582 | |
// Parse CRON frequency | |
// Break it down like James Brown | |
function parse_crontab($time, $crontab) { | |
// Get current minute, hour, day, month, weekday | |
$time = explode(' ', date('i G j n w', strtotime($time))); | |
// Split crontab by space | |
$crontab = explode(' ', $crontab); | |
// Foreach part of crontab | |
foreach ($crontab as $k => &$v) { | |
// Remove leading zeros to prevent octal comparison, but not if number is already 1 digit | |
$time[$k] = preg_replace('/^0+(?=\d)/', '', $time[$k]); | |
// 5,10,15 each treated as seperate parts | |
$v = explode(',', $v); | |
// Foreach part we now have | |
foreach ($v as &$v1) { | |
// Do preg_replace with regular expression to create evaluations from crontab | |
$v1 = preg_replace( | |
// Regex | |
array( | |
// * | |
'/^\*$/', | |
// 5 | |
'/^\d+$/', | |
// 5-10 | |
'/^(\d+)\-(\d+)$/', | |
// */5 | |
'/^\*\/(\d+)$/' | |
), | |
// Evaluations | |
// trim leading 0 to prevent octal comparison | |
array( | |
// * is always true | |
'true', | |
// Check if it is currently that time, | |
$time[$k] . '===\0', | |
// Find if more than or equal lowest and lower or equal than highest | |
'(\1<=' . $time[$k] . ' and ' . $time[$k] . '<=\2)', | |
// Use modulus to find if true | |
$time[$k] . '%\1===0' | |
), | |
// Subject we are working with | |
$v1 | |
); | |
} | |
// Join 5,10,15 with `or` conditional | |
$v = '(' . implode(' or ', $v) . ')'; | |
} | |
// Require each part is true with `and` conditional | |
$crontab = implode(' and ', $crontab); | |
// Evaluate total condition to find if true | |
return eval('return ' . $crontab . ';'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment