给 thinkphp 6 的通知任务增加一个只读控制台命令,可以先预览当前到期的待处理记录。命令只输出记录 id 和返回数量,适合在安排正式发送前核对筛选条件。
用待处理状态和到期时间筛选
假定 notification_jobs 含 id、status 和 due_at,due_at 与应用时间使用同一时区。将以下代码保存到 app/command/NotifyPreview.php。
<?php namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
class NotifyPreview extends Command
{
protected function configure()
{
$this->setName('notify:preview')->setDescription('Preview due jobs');
}
protected function execute(Input $input, Output $output)
{
$ids = Db::name('notification_jobs')
->where('status', 'pending')
->where('due_at', 'order('id', 'asc')
->limit(20)
->column('id');
$output->writeln('Preview count: ' . count($ids));
$output->writeln('IDs: ' . implode(', ', $ids));
return 0;
}
}

结果最多 20 条。这个数量表示本次预览返回的条数,不能当作所有待发送记录的总数。
注册命令并手动跑一次
将 commands 项合并进已有 config/console.php 配置。
return [
'commands' => [
'notify:preview' => \app\command\NotifyPreview::class,
],
];

在项目根目录执行 php think notify:preview,确认未来任务和已发送任务都没有进入预览。
定时检查时使用固定执行环境
如果需要定时记录预览结果,可将以下示例路径换成实际路径后放进系统定时任务。
*/10 * * * * cd /srv/example && /usr/bin/php think notify:preview >> /var/log/notify-preview.log 2>&1
先用定时任务所用的系统账号手动运行,确认 PHP 路径、数据库配置和日志权限正确。用测试数据核对空队列时输出 0。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











