«
Laravel Console Crontab 实现数据库备份

时间:2021-7-17    作者:网络剑客    分类: mysql


php artisan make:command BackupDatabase 创建一个命令, 代码如下:```

<?php

namespace App\Console\Commands;
use Symfony\Component\Process\Process;
use Illuminate\Console\Command;
use Symfony\Component\Process\Exception\ProcessFailedException;

/**
 * 备份数据库
 * Class BackupDatabase
 * @package App\Console\Commands
 */
class BackupDatabase extends Command
{
    protected $signature = 'db:backup';

    protected $description = 'Backup the database';

    protected $process;

    public function __construct()
    {
        parent::__construct();
        $backup_dir = config('database.db_backup_dir');
        $backup_file = $backup_dir .  '/' . date('Y-m-d H:i:s', time()) . '.sql';
        $this->createDirIsNotExists($backup_dir);
        $this->deleteExpireFile($backup_dir);
        $this->backup($backup_file);
    }

    /**
     * 备份目录不存在则创建
     * @param $backup_dir
     */
    private function createDirIsNotExists($backup_dir)
    {

        if (!\File::exists($backup_dir)){
            \File::makeDirectory($backup_dir);
        }
    }

    /**
     * 删除已过期的备份文件
     * @param $back_up_dir
     */
    private function deleteExpireFile($back_up_dir)
    {
        $expire_day = config('database.db_backup_expire_day'); 
        $end_date = date('Y-m-d H:i:s', strtotime("-{$expire_day} day")); // 小于该时间的文件则已过期
        $file_list = \File::allFiles($back_up_dir);
        foreach ($file_list as $file){
            if ($file->getATime() < strtotime($end_date)){
                \File::delete($file->getRealPath());
            }
        }
    }

    /**
     * 进行备份
     * @param $backup_file
     */
    private function backup($backup_file)
    {
        $this->process = new Process(sprintf(
            "mysqldump -h%s -u%s -p%s %s > '%s'",
            config('database.connections.mysql.host'),
            config('database.connections.mysql.username'),
            config('database.connections.mysql.password'),
            config('database.connections.mysql.database'),
            $backup_file
        ));
    }

    /**
     *
     */
    public function handle()
    {
        try {
            $this->process->mustRun();
            $this->info('The backup has been proceed successfully.');
        } catch (ProcessFailedException $exception) {
            $this->error('The backup process has been failed.');
        }

    }
}

config/database.php 添加两行配置:

   'db_backup_dir' => env('DB_BACKUP_DIR', './backup'),  // 指定数据库备份目录
    'db_backup_expire_day' => env('DB_BACKUP_EXPIRE_DAY', 30), // 指定数据库备份文件的有效时间(天), 默认30天!

大部分人习惯使用crontab -e直接编辑crontab配置,默认的crontab目录有:/etc/cron.daily, /etc/cron.hourly等等, 该目录
分别对应每天丶每小时等执行一次。

在/etc/cron.daily目录建建立一个shell文件db_backup:

   'db_backup_dir' => env('DB_BACKUP_DIR', './backup'),  // 指定数据库备份目录
    'db_backup_expire_day' => env('DB_BACKUP_EXPIRE_DAY', 30), // 指定数据库备份文件的有效时间(天), 默认30天!

#!/bin/bash
php xxxx/artisan db:backup
添加执行权限: chmod +x db_backup

标签: mysql laravel