thinkphp项目可通过内置调度器实现ai任务自动执行:启用schedule:run命令、创建aidailyreport命令类、在app/schedule.php中配置dailyat定时规则,并用supervisor常驻运行schedule:work进程。

你需要让ThinkPHP项目每天固定时间自动执行AI相关任务,比如调用大模型API生成日报、分析用户行为数据并输出洞察、或批量处理上传的文档内容,全程无需人工干预,也不依赖Linux crontab等外部调度器。
启用框架内置调度器
进入项目根目录,运行php think list,确认输出中包含schedule:run命令;若无,说明调度功能未启用。
打开app/command.php,在return数组末尾添加一行:
'schedule:run' => \think\scheduler\ScheduleCommand::class;
这一步漏掉会导致后续所有定时任务完全不执行。【必须写在return数组内部,且类名拼写不能有空格或大小写错误】
执行php think schedule:run验证——它不会真正执行任务,但能确认命令已注册成功。
创建AI任务命令类
在app/command/目录下新建文件AiDailyReport.php,内容如下:
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class AiDailyReport extends Command
{
protected function configure()
{
$this->setName('ai:daily-report')
->setDescription('调用大模型生成运营日报');
}
protected function execute(Input $input, Output $output)
{
// 示例:查询昨日订单+用户活跃数据
$data = \think\Db::name('order')->where('create_time', 'between', [strtotime('yesterday'), time()])->select();
// 调用你封装好的AI服务(如调用通义千问API)
$result = \app\common\service\AIService::generateReport($data);
$output->writeln('AI日报已生成:' . $result['url']);
}
}
注意:AI服务调用逻辑必须封装在独立类中,避免把密钥和请求细节直接写进命令类。
注册调度规则
第一步:确保app/provider.php的return数组中已加入:
think\scheduler\ScheduleServiceProvider::class
第二步:在项目根目录下创建app/schedule.php,内容为:
use think\scheduler\Schedule;
return function (Schedule $schedule) {
$schedule->command('ai:daily-report')->dailyAt('08:30');
;
其中ai:daily-report必须与上一步configure()中$this->setName()的值完全一致,字母大小写敏感。
启动常驻调度进程
① 在服务器上安装supervisor(如Ubuntu系统执行:apt install supervisor)
② 创建supervisor配置文件/etc/supervisor/conf.d/think-ai-scheduler.conf,内容如下:
[program:think-ai-scheduler]
command=php /var/www/myapp/think schedule:work
directory=/var/www/myapp
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/log/think-ai-scheduler.log
③ 重载supervisor配置:supervisorctl reread && supervisorctl update
④ 启动进程:supervisorctl start think-ai-scheduler
这一步必须使用绝对路径,否则schedule:work无法加载app/schedule.php,导致任务注册失效。【/var/www/myapp需替换为你真实的项目绝对路径】
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











