Linux 系統 cron 是標準任務調度工具,但某些場景需在 PHP 內部實現調度:共享主機無 crontab 權限、跨平台部署 (Windows)、動態任務管理、任務狀態監控、Web 介面配置。本文實現純 PHP Cron 解析器與調度器,支援標準 Cron 表達式、進程分離、殭屍進程防護。
* * * * * 執行命令
- - - - -
| | | └─ 星期幾 (0-7) (Sun=0 或 7)
| | └──── 月份 (1-12)
| └────── 日期 (1-31)
└──────── 小時 (0-23)
└──────── 分鐘 (0-59)
特殊符號:
* 所有值
, 列表值 (1,3,5)
- 範圍 (1-5)
/ 步長 (*/15 = 每 15 分鐘)
<?php
/**
* Cron 表達式解析器:計算下次執行時間
*/
class CronExpression
{
public function __construct(
private string $expression,
private DateTimeZone $timezone = new DateTimeZone('UTC')
) {
$this->validate();
}
public function getNextRunDate(DateTime $from = null, int $nth = 1): DateTime
{
$from ??= new DateTime('now', $this->timezone);
$from = clone $from;
$from->setTimezone($this->timezone);
// 向前推進到下一分鐘
$from->modify('+1 minute');
$from->setSecond(0);
for ($i = 0; $i < $nth; $i++) {
$from = $this->findNext($from);
if ($i < $nth - 1) {
$from->modify('+1 minute');
}
}
return $from;
}
public function isDue(DateTime $date = null): bool
{
$date ??= new DateTime('now', $this->timezone);
$next = $this->getNextRunDate($date);
return $next->format('Y-m-d H:i') === $date->format('Y-m-d H:i');
}
private function validate(): void
{
$parts = preg_split('/\s+/', trim($this->expression));
if (count($parts) !== 5) {
throw new InvalidArgumentException("Cron 表達式需 5 欄位: {$this->expression}");
}
[$this->min, $this->hour, $this->dom, $this->month, $this->dow] = $parts;
}
private function findNext(DateTime $date): DateTime
{
$date = clone $date;
$maxIterations = 366 * 24 * 60; // 最多搜尋一年
for ($i = 0; $i < $maxIterations; $i++) {
if ($this->match($date)) {
return $date;
}
$date->modify('+1 minute');
}
throw new RuntimeException("無法在一年內找到匹配時間: {$this->expression}");
}
private function match(DateTime $date): bool
{
return $this->matchField($date->format('i'), $this->min) &&
$this->matchField($date->format('G'), $this->hour) &&
$this->matchField($date->format('j'), $this->dom) &&
$this->matchField($date->format('n'), $this->month) &&
$this->matchField($date->format('w'), $this->dow); // 0=Sun
}
private function matchField(string $value, string $pattern): bool
{
if ($pattern === '*') return true;
foreach (explode(',', $pattern) as $part) {
if (str_contains($part, '/')) {
[$range, $step] = explode('/', $part);
$step = (int)$step;
} else {
$range = $part;
$step = 1;
}
if (str_contains($range, '-')) {
[$min, $max] = explode('-', $range);
} else {
$min = $max = $range;
}
$val = (int)$value;
if ($val >= (int)$min && $val <= (int)$max && ($val - $min) % $step === 0) {
return true;
}
}
return false;
}
}
?>
<?php
/**
* PHP Cron 調度器
* 用法:每分鐘由系統 cron 呼叫一次 php scheduler.php
* 或使用常駐進程模式 (需 pcntl 擴展)
*/
class PhpCronScheduler
{
public function __construct(
private string $crontabFile,
private string $phpBinary = 'php',
private int $maxParallel = 10
) {}
public function run(): void
{
$now = new DateTime('now', new DateTimeZone('UTC'));
$crontab = file($this->crontabFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$running = 0;
foreach ($crontab as $line) {
if ($running >= $this->maxParallel) break;
$line = trim($line);
if ($line === '' || $line[0] === '#') continue;
try {
[$min, $hour, $dom, $month, $dow, $command] = preg_split('/\s+/', $line, 6);
$expr = implode(' ', [$min, $hour, $dom, $month, $dow]);
$cron = new CronExpression($expr);
if ($cron->isDue($now)) {
$this->executeCommand($command);
$running++;
}
} catch (Throwable $e) {
error_log("Cron 解析錯誤: {$line} - {$e->getMessage()}");
}
}
}
private function executeCommand(string $command): void
{
// 使用 pcntl_fork 背景執行,避免阻塞主進程
$pid = pcntl_fork();
if ($pid === -1) {
error_log("Fork 失敗: {$command}");
return;
}
if ($pid > 0) {
// 父進程:非阻塞等待,防殭屍進程
pcntl_signal(SIGCHLD, fn() => pcntl_wait($status, WNOHANG));
return;
}
// 子進程:執行命令
// 重定向輸出避免干擾
$descriptors = [
0 => ['pipe', 'r'],
1 => ['file', '/dev/null', 'w'],
2 => ['file', '/var/log/php-cron-error.log', 'a'],
];
$proc = proc_open($command, $descriptors, $pipes);
if ($proc) {
proc_close($proc);
}
exit(0);
}
}
// === 入口腳本 scheduler.php ===
require_once 'vendor/autoload.php'; // 或 require 類別檔案
$scheduler = new PhpCronScheduler(__DIR__ . '/crontab');
$scheduler->run();
?>
# 格式:分 時 日 月 週 命令
# 每分鐘執行一次
* * * * * /usr/bin/php /var/www/app/artisan schedule:run >> /dev/null 2>&1
# 每天凌晨 2:30 備份資料庫
30 2 * * * /usr/bin/mysqldump -u backup -p'secret' dbname | gzip > /backup/db_$(date +\%Y\%m\%d).sql.gz
# 每週一早上 6 點發送週報
0 6 * * 1 /usr/bin/php /var/www/app/scripts/weekly_report.php
# 每月 1 號 0:00 清理臨時檔
0 0 1 * * find /var/www/app/tmp -type f -mtime +7 -delete
# crontab -e
* * * * * /usr/bin/php /var/www/app/scheduler.php >> /var/log/php-cron.log 2>&1
<?php
// daemon.php - 長期運行進程
declare(ticks=1);
$running = true;
pcntl_signal(SIGTERM, fn() => $running = false);
pcntl_signal(SIGINT, fn() => $running = false);
$scheduler = new PhpCronScheduler(__DIR__ . '/crontab');
while ($running) {
$start = microtime(true);
$scheduler->run();
$elapsed = microtime(true) - $start;
$sleep = max(1, 60 - $elapsed); // 保證每分鐘執行一次
sleep($sleep);
}
?>
管理命令:
# 啟動
nohup php daemon.php > /var/log/php-cron-daemon.log 2>&1 &
# 停止
pkill -f daemon.php
# 系統服務化
# /etc/systemd/system/php-cron.service
[Unit]
Description=PHP Cron Scheduler
After=network.target
[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/php daemon.php
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
<?php
// 擴展:任務執行記錄
class CronLogger
{
public function log(string $command, int $exitCode, float $duration, string $output = ''): void
{
$log = [
'time' => date('c'),
'command' => $command,
'exit_code' => $exitCode,
'duration_ms' => round($duration * 1000, 2),
'memory_mb' => round(memory_get_peak_usage(true) / 1024 / 1024, 2),
];
error_log(json_encode($log, JSON_UNESCAPED_UNICODE), 3, '/var/log/php-cron-jobs.log');
}
}
// 整合到 executeCommand
$start = microtime(true);
$proc = proc_open($command, $descriptors, $pipes);
$exitCode = proc_close($proc);
$duration = microtime(true) - $start;
$output = stream_get_contents($pipes[1] ?? fopen('php://memory', 'r'));
(new CronLogger())->log($command, $exitCode, $duration, $output);
?>
| 庫 | 特點 | 適用場景 |
|---|---|---|
dragonmantank/cron-expression | 純解析器、Composer 安裝、廣泛使用 | 需自行實作調度器 |
lavary/crunz | 完整調度器、Laravel 風格、支援並行 | 獨立專案、需 Web UI |
symfony/scheduler | Symfony 整合、Messenger 整合 | Symfony 專案 |
spatie/laravel-schedule-monitor | 監控 Laravel 排程 | Laravel 專案 |
本文實現了完整的 PHP Cron 調度系統:標準 5 欄位表達式解析、下次執行時間計算、pcntl_fork 背景執行、殭屍進程防護、系統 Cron 與常駐進程兩種部署模式、結構化日誌監控。生產環境建議直接使用成熟庫 dragonmantank/cron-expression + 系統 Cron,僅在受限環境或需動態管理時使用自建方案。