项目中有时需要定期执行一些周期性的任务,比如数据备份、清楚日志等,Laravel 的命令行调度器允许你在 Laravel 中清晰明了地定义命令调度。
新建命令行调度器:
1
| php artisan make:command Backup
|
编辑 app/Console/Commands/Backup.php :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <?php
namespace App\Console\Commands;
use Illuminate\Console\Command; use Illuminate\Support\Facades\Log;
class Backup extends Command {
protected $signature = 'backup:run';
protected $description = '项目备份';
public function handle() { Log::info('测试 backup:run'); return Command::SUCCESS; } }
|
在 app/Console/Kernel.php 中注册:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel { protected function schedule(Schedule $schedule) { $schedule->command('back:up')->hourly(); } }
|
使用服务器的定时命令 cron 运行 php artisan schedule:run,在你的服务器端配置, 例如:
1
| * * * * * cd /home/vagrant/code/laravel-demo && php artisan schedule:run >> /dev/null 2>&1
|
每分钟运行一次 php artisan schedule:run 命令。
通过命令 php artisan schedule:list 查看注册的定时任务:

Demo:https://github.com/hefengbao/laravel-demo