ThinkPHP6需借助第三方扩展yzh52521/schedule实现定时任务调度;安装后执行php think schedule:init生成ConsoleScheduling.php,配置命令类并注册到app/event.php,通过系统Cron每分钟调用php think schedule:run触发任务。

ThinkPHP6 本身不内置任务调度器,但可通过第三方扩展 yzh52521/schedule(常称 think-schedule)实现类似 Laravel 的链式定时任务管理。它不是官方组件,需手动引入,但结构清晰、兼容 TP6.x,是目前社区较主流的调度增强方案。
安装与初始化
在项目根目录执行:
composer require yzh52521/schedule
安装完成后运行初始化命令:
php think schedule:init
该命令会在 app/ 目录下生成 ConsoleScheduling.php 类,这是调度入口文件,用于定义所有计划任务。
还需确保事件监听已注册:打开 app/event.php,在 'AppInit' 事件监听数组中加入该类:
'AppInit' => [\app\ConsoleScheduling::class]
定义可调度的命令类
你的任务逻辑必须封装为标准 ThinkPHP 命令类,路径为 app/command/(TP6.0+ 推荐),类需继承 think\console\Command,并在 configure() 中显式设置名称:
- 命名空间为
app\command - 使用
$this->setName('task:send')注册命令名(如task:send) - 务必在
handle()或execute()中写实际逻辑,避免调用exit()或die()
例如:app/command/SendReport.php
namespace app\command;
<p>use think\console\Command;
use think\console\Input;
use think\console\Output;</p><p>class SendReport extends Command
{
protected function configure()
{
$this->setName('report:send')
->setDescription('Send daily report email');
}</p><pre class="brush:php;toolbar:false;">protected function execute(Input $input, Output $output)
{
// 实际发送逻辑,可直接调用模型、Db 等
\think\Db::name('logs')->whereTime('create_time', '-1 day')->delete();
$output->writeln('Report sent.');
}
}
在 ConsoleScheduling 中配置调度规则
打开刚生成的 app/ConsoleScheduling.php,在 schedule() 方法中使用 $schedule 对象链式注册任务:
- 调用已有命令:
$schedule->command('report:send')->dailyAt('09:00'); - 执行系统命令:
$schedule->exec('echo "hello" >> /tmp/schedule.log')->everyMinute(); - 执行闭包:
$schedule->call(function () { cache('last_run', time()); })->hourly(); - 限制单服务器执行(防集群重复):
->onOneServer()
注意:所有时间方法(如 daily()、everyFiveMinutes())底层仍依赖外部 Cron 每分钟触发 php think schedule:run,不能脱离系统定时器独立运行。
启用并验证调度
确认以下几项全部满足,否则任务不会被识别或执行:
- 运行
php think list,看到你的命令(如report:send)出现在列表中 - 检查
app/config/console.php中'scheduling' => true已开启(TP8 要求,TP6 可选但建议保持一致) - 开发环境默认跳过调度,临时测试可加参数:
php think schedule:run -v --env=local - 最终上线必须配置 Linux Cron:
* * * * * cd /path/to/project && /usr/bin/php think schedule:run >> /dev/null 2>&1
运行 php think schedule:list 可查看所有已注册任务及其下次预计执行时间,这是唯一可信的调度状态检查方式。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











