laravel 任務排程實戰 資料庫備份
我們要一分鐘備份一次資料庫。讓我們開始吧。
建立命令檔案
php artisan make:comman BackupDatabase
開啟剛剛建立的檔案,並修改為以下內容:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Process; class BackupDatabase extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'db:backup'; /** * The console command description. * * @var string */ protected $description = 'Backup the database'; protected $process; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); $file_name = date('Y-m-d-H:i:s') . '-' . config('database.connections.mysql.database') . '.sql'; $this->process = new Process(sprintf('mysqldump -u%s --password=%s %s > %s', config('database.connections.mysql.username'), config('database.connections.mysql.password'), config('database.connections.mysql.database'), storage_path('backups/' . $file_name) )); } /** * Execute the console command. * * @return mixed */ public function handle() { try { $this->process->mustRun(); $this->info('The backup has been proceed successfully.'); } catch (ProcessFailedException $exception) { $this->error($exception); } } }
配置命令
在storage建立一個backups資料夾,開啟app/Console/Kernel.php
修改schedule方法,如下
protected function schedule(Schedule $schedule) { $schedule->command('db:backup') ->everyMinute(); }
伺服器配置
進入伺服器 執行
crontab -e
如果是第一次開啟crontab的話,會讓你選擇編輯器,這裡(選vim)就可以了,我選的第三個。但是如果你選錯了,就可能會遇到點麻煩,沒有辦法正常編輯,crontab -e。 怎麼辦?
執行這個命令:select-editor (針對crontab的一個命令), 可以讓你重新選一次。
複製如下內容
* * * * * php /home/vagrant/code/laravel/artisan schedule:run >> /dev/null 2>&1
/home/vagrant/code/laravel/ 是專案的目錄
一分鐘後可以檢查storage/backups資料夾內是否有生成備份的sql檔案。