|
Laravel如何实现定时任务?本文主要介绍了Laravel实现定时任务的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望对大家有所帮助。 简介 定时任务是后端开发过程中一项十分常见的需求,常出现在数据统计、垃圾信息清理等场景中。Laravel 提供了一整套的定时任务工具,让我们只需要专注地完成逻辑,剩下的基础工作将由它来承担。 基本用法 生成命令 php artisan make:command AreYouOK 5.2 及之前的版本,此命令为 `php artisan make:console xxx` 编辑命令 编辑 `app/Console/Commands/AreYouOK.php` 文件,修改如下几处: ... ...
protected $signature = 'areyou:ok'; // 命令名称
protected $description = '雷军,科技圈最会唱歌的男人'; // 命令描述,没什么用
public function __construct()
{
parent::__construct();
// 初始化代码写到这里,也没什么用
}
public function handle()
{
// 功能代码写到这里
}注册命令 编辑 `app/Console/Kernel.php` 文件,将新生成的类进行注册: protected $commands = [
AppConsoleCommandsAreYouOK::class,
]; 编写调用逻辑: protected function schedule(Schedule $schedule)
{
$schedule->command('areyou:ok')
->timezone('Asia/Shanghai')
->everyMinute();
}上面的逻辑是每分钟调用一次。Laravel 提供了从一分钟到一年的各种长度的时间函数,直接调用即可。 把这个 Laravel 项目注册到系统的 cron 里 编辑 `/etc/crontab` 文件,加入如下代码: * * * * * root /usr/bin/php /var/www/xxxlaravel/artisan schedule:run >> /dev/null 2>&1 上面一行中的 `/var/www/xxxlaravel` 需要改为实际的路径。 fire 重启 cron 激活此功能:`systemctl restart crond.service`,搞定!
|