在 Ubuntu 上给 ThinkPHP 配置定时任务,通常有两种常见方式:
ThinkPHP 支持自定义命令(Command)。
示例(ThinkPHP 6):
php think make:command Hello
生成文件:app/command/Hello.php
修改 Hello.php:
protected function configure()
{
$this->setName('hello')
->setDescription('定时任务示例');
}
protected function execute(Input $input, Output $output)
{
// 你的业务逻辑
$output->writeln('Hello Cron');
}
注册命令:app/command.php
return [
'app\command\Hello',
];
测试命令:
php think hello
编辑定时任务:
crontab -e
添加一行(每5分钟执行一次):
*/5 * * * * /usr/bin/php /var/www/yourproject/think hello >> /tmp/think.log 2>&1
说明:
/usr/bin/php:PHP 路径(用 which php 查看)/var/www/yourproject:项目根目录>> /tmp/think.log:日志输出sudo service cron restart
ThinkPHP 6 支持类似 Laravel 的 任务调度。
app/Schedule.php
use think\facade\Schedule;
Schedule::command('hello')->everyMinute();
* * * * * /usr/bin/php /var/www/yourproject/think schedule:run >> /tmp/schedule.log 2>&1
✅ 优点:
which php
确保 crontab 使用绝对路径
chown -R www-data:www-data /var/www/yourproject
date_default_timezone_set('Asia/Shanghai');
| 场景 | 推荐方式 |
|---|---|
| 简单任务 | Linux Cron + think command |
| 多任务管理 | ThinkPHP Schedule |
| 生产环境 | Cron + 日志 |
如果你用的是 ThinkPHP 5 / 5.1 / 6 / 8,可以告诉我版本,我可以给你更精确的示例。