tp5使用定时脚本备份数据库!

2019-10-14  本文已影响0人  DragonersLi

gitHub包地址:https://github.com/cocolait/backup

一、引入包:composer require cocolait/backup

二、脚本代码编写:

1.command.php下return数组添加:'app\admin\command\Backup', #数据库备份
2.command目录下新建Backup.php,内容如下:
<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;
class Backup extends Command
{



    //定义任务名和描述
    protected function configure(){

        $this
            // 命令的名字("php think" 后面的部分)
            ->setName('backup')
            // 运行 "php think list" 时的简短描述
            ->setDescription("php think backup 备份mysql数据库");

    }

    //调用该类时,会自动运行execute方法
    protected function execute(Input $input, Output $output){
      set_time_limit(0);
      ini_set('memory_limit','5000M');

// backup($path = '备份路径', $tableArray = [需要备份的表集合], $bool = '是否同时备份数据 默认false',['is_compress' => '是否写入内容文件进行压缩','is_download' => '是否进行下载'])

        // 配置项-----必传值
        $config = [
            // 服务器地址
            'host'        => Config('database.hostname'),
            // 数据库名
            'database'    => Config('database.database'),
            // 用户名
            'user'        => Config('database.username'),
            // 密码
            'password'    => Config('database.password'),
            // 端口
            'port'        => Config('database.hostport'),
            // 字符编码
            'charset'     => Config('database.charset')
        ];
    // 备份
        $dir = "./backup/sql";//备份路径
        $data = \cocolait\sql\Backup::instance($config)->backUp($dir,[],true,['is_compress' => 0]);
        var_dump($data);

    // 还原
        #$data = cocolait\sql\Backup::instance($config)->recover('xxx_20180512072455_194757120.sql',$dir);
       # print_r($data);die;



    }




}

3.本地测试备份
执行php think backup成功只有返回如下信息:
image.png
项目根目录下backup/sql下生成备份sql!,恢复sql同理,代码略!
image.png
4.上传代码至linux服务器,添加定时任务:每天4:00执行备份,并记录执行命令日志

0 4 * * * root /usr/local/php/bin/php /home/wwwroot/paijinhua/think backup >> /home/wwwroot/paijinhua/crontab.log 2>&1

image.png
上一篇 下一篇

猜你喜欢

热点阅读