在 Ubuntu 中给 ThinkPHP 配置定时任务,通常有两种常见方式:
下面分别说明。
在 ThinkPHP 中创建一个命令行脚本:
php think make:command Hello
生成的文件在:
app/command/Hello.php
示例:
protected function configure()
{
$this->setName('hello')
->setDescription('定时任务示例');
}
protected function execute(Input $input, Output $output)
{
// 你的业务逻辑
$output->writeln('hello task run');
}
注册命令(app/command.php):
return [
'app\command\Hello',
];
测试命令:
php think hello
编辑定时任务:
crontab -e
添加一行(假设项目在 /var/www/project):
* * * * * php /var/www/project/think hello >> /var/www/project/runtime/cron.log 2>&1
含义:
runtime/cron.log常用示例:
# 每天凌晨 1 点
0 1 * * * php /var/www/project/think hello
# 每 5 分钟
*/5 * * * * php /var/www/project/think hello
php 要使用绝对路径(如 /usr/bin/php)runtime 目录可写tail -f /var/www/project/runtime/cron.log
ThinkPHP 6.1 提供了 Schedule 调度器。
composer require topthink/think-schedule
在 app/schedule/Task.php:
use think\schedule\Schedule;
return function (Schedule $schedule) {
$schedule->command('hello')
->everyMinute()
->appendOutputTo(runtime_path() . 'schedule.log');
};
只需一条:
* * * * * php /var/www/project/think schedule:run
框架会自动调度任务。
/var/log/cron(CentOS)或 journalctl -u cronchown -R www-data:www-data /var/www/project
chmod -R 755 runtime
如果你使用的是 ThinkPHP 5.x 或 具体版本,可以告诉我,我可以给你对应示例。