PHP code example of yunadmin / cron-schedule
1. Go to this page and download the library: Download yunadmin/cron-schedule library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
yunadmin / cron-schedule example snippets
use YunAdmin\CronSchedule\CronExpression;
// 解析一个 5 段表达式
$cron = CronExpression::parse('0 0 * * *');
// 下次运行时间(返回 DateTimeImmutable)
$next = $cron->getNextRunDate();
echo $next->format('Y-m-d H:i:s');
// 上一次运行时间
$prev = $cron->getPreviousRunDate();
// 当前时间是否到期(命中)
if ($cron->isDue()) {
// 执行任务……
}
use YunAdmin\CronSchedule\CronExpression;
// 5 段(默认)
$cron = CronExpression::parse('30 8 * * 1-5'); // 工作日 08:30
// 6 段(含秒):第三个参数传 true
$sec = CronExpression::parse('*/20 * * * * *', null, true); // 每 20 秒一次
// 也可以在已有表达式上切换为秒级模式(返回新实例,不影响原对象)
$cronWithSeconds = $cron->withSeconds();
CronExpression::parse('@daily'); // 等价于 0 0 * * *
CronExpression::parse('@hourly'); // 等价于 0 * * * *
CronExpression::parse('@weekly'); // 等价于 0 0 * * 0
// 下一次(默认从当前时间算)
$next = $cron->getNextRunDate();
// 从指定时间算下一次
$next = $cron->getNextRunDate('2026-08-24 08:07:00');
// 跳过前 n 次命中:取第 n 个之后的运行时间
$next3rd = $cron->getNextRunDate('now', 2); // 跳过前 2 次,返回第 3 次
// 允许返回与基准时间相同的结果(即基准时间本身即命中)
$next = $cron->getNextRunDate('now', 0, true);
// 指定时区(不影响传入的 DateTime 对象)
$next = $cron->getNextRunDate('now', 0, false, 'Asia/Shanghai');
// 上一次运行时间(参数含义与 getNextRunDate 一致)
$prev = $cron->getPreviousRunDate();
$prev = $cron->getPreviousRunDate('2026-08-24 08:07:00');
// 批量获取多个运行时间
$dates = $cron->getMultipleRunDates(5); // 返回包含 5 个 DateTimeImmutable 的数组
// 判断表达式在「当前时间」是否命中
$cron->isDue();
// 判断指定时间是否命中
$cron->isDue('2026-08-27 00:00:00');
$cron->isDue(new \DateTimeImmutable('2026-08-27 00:00:00'));
// 语法是否合法(返回 bool)
CronExpression::isValidExpression('0 0 * * *'); // true
CronExpression::isValidExpression('99 0 * * *'); // false
CronExpression::isValidExpression('0 0 0 * * *', true);// 6 段需传 true
use YunAdmin\CronSchedule\ExpressionFormatter;
$fmt = new ExpressionFormatter();
// 规范化:列表按语义排序、字面量统一大写,便于比较
$fmt->normalize(CronExpression::parse('0 0 * DEC,JAN *')); // 输出 "0 0 * JAN,DEC *"
// 人类可读描述
$fmt->describe(CronExpression::parse('@daily')); // "At 0:0 every day"
$fmt->describe(CronExpression::parse('0 0 15W * *')); // "At 0:0 on the nearest weekday to day 15 of the month"
use YunAdmin\CronSchedule\Exception\InvalidExpressionException;
use YunAdmin\CronSchedule\Exception\UnreachableExpressionException;
try {
CronExpression::parse('0 0 30 2 *')->getNextRunDate(); // 二月没有 30 天
} catch (UnreachableExpressionException $e) {
// 表达式永远不可能匹配任何日期
echo $e->getMessage();
}
try {
CronExpression::parse('99 0 * * *');
} catch (InvalidExpressionException $e) {
// 表达式语法或取值非法
echo $e->getMessage();
}