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

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

一、创建 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容