在ThinkPHP框架中,可以通过使用Crontab
类实现Cron任务调度。具体步骤如下:
application/command
目录下创建一个继承think\console\Command
的命令类,例如Cron
类。
namespace app\command;
use think\console\Command; use think\console\Input; use think\console\Output;
class Cron extends Command { protected function configure() { $this->setName('cron')->setDescription('Cron Task'); }
protected function execute(Input $input, Output $output)
{
// 执行Cron任务的代码
}
}
2. 在`application/command.php`中注册该命令类。
```php
return [
app\command\Cron::class,
];
Crontab
类中设置Cron任务调度规则,例如每分钟执行一次。
namespace app\command;
use think\console\Command; use think\console\Input; use think\console\Output; use think\console\Scheduling\Event; use think\console\Scheduling\Schedule;
class Crontab { public function schedule(Schedule $schedule) { $schedule->command('cron')->everyMinute(); } }
4. 在`app/service.php`中注册`Crontab`类。
```php
return [
\think\console\Crontab::class,
];
php think crontab
命令即可。总结:在ThinkPHP框架中,通过创建命令类、注册命令类、设置调度规则、注册Crontab类和配置服务器Cron任务调度,可以实现Cron任务的调度。