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
修改部分内容,如下

protected $commands = [
       
        Commands\BackupDatabase::class,
    ];
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文件。

    原文作者:北方
    原文地址: https://segmentfault.com/a/1190000018018602
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞