Created
August 27, 2018 08:00
-
-
Save zhuravljov/49967441c6294b2fe325ba1fb4402607 to your computer and use it in GitHub Desktop.
Эмулятор Cron для докер Docker-контейнера
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
#!/usr/bin/env php | |
<?php | |
/** | |
* Скрипт для запуска команды по расписанию, для замены cron-а в сети из docker-контейнеров. | |
* | |
* Пример команды, которая будет запускаться каждую минуту: | |
* docker/php/cron.php "* * * * *" php yii rate/update | |
* | |
* Зависимости: | |
* "mtdowling/cron-expression": "~1.2.0" | |
* | |
* @author Roman Zhuravlev <[email protected]> | |
*/ | |
require(__DIR__ . '/../../vendor/autoload.php'); | |
// Params | |
$params = $_SERVER['argv']; | |
array_shift($params); | |
$expression = array_shift($params); | |
$command = implode(' ', $params); | |
$schedule = \Cron\CronExpression::factory($expression); | |
// Signal handler | |
$signal = 0; | |
$signalHandler = function ($sigNum) use (&$signal) { | |
$signal = $sigNum; | |
}; | |
pcntl_signal(SIGTERM, $signalHandler); | |
pcntl_signal(SIGINT, $signalHandler); | |
// Loop | |
printLog('Cron started'); | |
while (true) { | |
sleep(60 - time() % 60); | |
pcntl_signal_dispatch(); | |
if ($signal) { | |
printLog("Cron stopped by signal $signal"); | |
exit(0); | |
} | |
if (!$schedule->isDue()) { | |
continue; | |
} | |
$startedAt = microtime(true); | |
printLog("[started] command: $command", $startedAt); | |
passthru($command, $exitCode); | |
$finishedAt = microtime(true); | |
$totalTime = sprintf('%01.3f', $finishedAt - $startedAt); | |
printLog("[finished] duration $totalTime s, exit code $exitCode"); | |
if ($exitCode) { | |
exit($exitCode); | |
} | |
} | |
function printLog($message, $time = null) | |
{ | |
echo date('Y-m-d H:i:s', $time ?? time()), ' ' , $message, PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment