laravel task scheduling actual database backup

Keywords: PHP Database MySQL crontab

We need to back up the database once a minute. Let's start.

Create command file

php artisan make:comman BackupDatabase

Open the file you just created and change it to the following:

<?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);
        }
    }
}

Configuration command

Create a backups folder in storage, and open app/Console/Kernel.php
Modify the schedule method as follows

protected function schedule(Schedule $schedule)
    {
        $schedule->command('db:backup')
            ->everyMinute();
    }

Server configuration

Enter server execution

crontab -e

If you open crontab for the first time, you will be asked to choose editor. Here (choose vim), I choose the third one. But if you choose the wrong one, you may have trouble editing it normally. What should I do?
Execute this command: select editor (a command for crontab), which allows you to select again.
Copy the following

* * * * * php /home/vagrant/code/laravel/artisan schedule:run >> /dev/null 2>&1

/home/vagrant/code/laravel / is the project directory
After one minute, you can check whether there are sql files in the storage/backups folder to generate backups.

Posted by dugindog on Mon, 02 Dec 2019 08:20:44 -0800