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文件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章