咱們要一分鐘備份一次數據庫。讓咱們開始吧。php
php artisan make:comman BackupDatabase
打開剛剛建立的文件,並修改成如下內容:mysql
<?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
修改部份內容,以下laravel
protected $commands = [ Commands\BackupDatabase::class, ]; protected function schedule(Schedule $schedule) { $schedule->command('db:backup') ->everyMinute(); }
進入服務器 執行sql
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文件。vim