美文网首页
Laravel实现定时任务示例(任务调度schedule)

Laravel实现定时任务示例(任务调度schedule)

作者: 别瞄我 | 来源:发表于2017-02-22 16:07 被阅读608次

这里以一个定时统计每天订单量的需求做示例

一、创建 Command 文件

  1. 输入命令 php artisan make:console CountDayOrders(即在app/Console/Commands 下创建了 CountDayOrders.php 文件,不嫌麻烦不怕出错的话可以自己手动创建)

  2. 完善 Command 信息(编辑CountDayOrders.php文件)

  • 签名
protected $signature = 'CountDayOrders';
  • 描述
protected $description = '统计每天的订单数';
  • 在 handle() 方法中实现功能
public function handle()
    {   
        //业务代码    
    }

二、在 Kernel.php 中注册命令并填写执行计划

  1. 注册命令CountDayOrders
# 在App\Console\Kernel.php文件中添加如下代码
protected $commands = [
            \App\Console\Commands\CountDayOrders::class,
];
  1. 填写执行计划(每天0点执行)
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('CountDayOrders')->daily();
    }

三、Linux配置定时任务

  1. 打开定时任务文件
crontab -e
  1. 加入如下语句
# 下面的php和artisan最好写绝对路径,php可以用 which php 命令查看位置,artisan 在项目根目录
 * * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1

参考链接:
http://laravelacademy.org/post/235.html
http://wiki.jikexueyuan.com/project/laravel-5.1/task-scheduling.html
http://www.cnblogs.com/zzdylan/p/5939170.html
http://www.jianshu.com/p/40fe9f1017f8

相关文章

网友评论

      本文标题:Laravel实现定时任务示例(任务调度schedule)

      本文链接:https://www.haomeiwen.com/subject/jglmwttx.html