thinkphp项目可通过内置调度器实现每日9点自动推送:需注册schedulecommand类、定义senddailypush命令、配置schedule.php并用supervisor常驻运行schedule:work进程。

你需要让ThinkPHP项目每天固定时间自动向用户推送行业资讯和待办事项,不依赖外部定时工具(如Linux crontab),也不手动触发,全部由框架自身调度完成。
启用ThinkPHP内置的命令行任务调度
进入项目根目录,执行 php think list,确认输出中包含 schedule:run 命令;若无,则说明未启用调度功能,需检查 app/command.php 是否已注册 think\scheduler\ScheduleCommand 类。
打开 app/command.php,在 return 数组中添加一行:'schedule:run' => \think\scheduler\ScheduleCommand::class;这一步漏掉会导致后续所有定时任务完全不执行。
运行 php think schedule:run 测试命令是否可识别——它不会立即执行任务,但能验证调度器已加载。
定义每日推送任务逻辑
在 app/command.php 同级目录新建 command/SendDailyPush.php,继承 \think\command\Command,重写 configure 和 execute 方法。
在 execute 方法中编写推送核心逻辑:先查出今日应推的行业资讯(例如从 news 表 where publish_time 在今天且 status=1),再查出用户当日待办(关联 user_todo 表,条件为 due_date = today() 且未完成);两组数据合并后调用统一推送接口(如企业微信机器人、短信网关或站内信服务)。
注意:数据库查询必须加 【where status = 1】 过滤,否则草稿状态的资讯也会被误推。
将任务注册进调度器
打开 app/provider.php,在 return 数组中追加:think\scheduler\ScheduleServiceProvider::class。
创建 app/schedule.php 文件,内容为:
<?php use think\scheduler\Schedule;return function (Schedule $schedule) { $schedule->command('send:daily-push')->dailyAt('09:00');};
其中 send:daily-push 是你上一步定义的命令名(需与 configure() 中设置的 $this->name 一致),dailyAt('09:00') 表示每天上午9点整触发。
启动常驻调度进程
第一步:确保服务器已安装 supervisor 或 systemd 等进程管理工具。
第二步:在项目根目录下执行 php think schedule:work,该命令会持续监听并按秒检查任务是否到期;它必须保持后台运行,一旦退出,定时推送即中断。
第三步:用 supervisor 管理该进程,配置示例中 command=php /var/www/myapp/think schedule:work 必须写绝对路径,否则 schedule:work 启动后无法定位到项目根目录下的 app/schedule.php,导致任务注册失效。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











