這里以一個定時統(tǒng)計每天訂單量的需求做示例
一造虎、創(chuàng)建 Command 文件
輸入命令
php artisan make:console CountDayOrders
(即在app/Console/Commands 下創(chuàng)建了 CountDayOrders.php 文件变丧,不嫌麻煩不怕出錯的話可以自己手動創(chuàng)建)完善 Command 信息(編輯CountDayOrders.php文件)
- 簽名
protected $signature = 'CountDayOrders';
- 描述
protected $description = '統(tǒng)計每天的訂單數(shù)';
- 在 handle() 方法中實現(xiàn)功能
public function handle()
{
//業(yè)務代碼
}
二攒发、在 Kernel.php 中注冊命令并填寫執(zhí)行計劃
- 注冊命令CountDayOrders
# 在App\Console\Kernel.php文件中添加如下代碼
protected $commands = [
\App\Console\Commands\CountDayOrders::class,
];
- 填寫執(zhí)行計劃(每天0點執(zhí)行)
protected function schedule(Schedule $schedule)
{
$schedule->command('CountDayOrders')->daily();
}
三呼伸、Linux配置定時任務
- 打開定時任務文件
crontab -e
- 加入如下語句
# 下面的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.reibang.com/p/40fe9f1017f8