Laravel定时任务备份数据库

结合Laravel特性,通过使用 artisan 命令进行封装,在定时任务中,做到非常方便的数据库备份

备份命令

php artisan make:comman命令来创建一个自定义命令

php artisan make:comman BackupDatabase

如下填写app\Console\Commands\BackupDatabase.php

process = new Process(sprintf(
            'mysqldump -u%s -p%s %s > %s',
            config('database.connections.mysql.username'),
            config('database.connections.mysql.password'),
            config('database.connections.mysql.database'),
            storage_path('../../backup.sql') //生成到项目文件夹外
        ));
    }

    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.');
        }
    }
}

定时脚本

定位Console/Kernel.php,commandsschedule如下添加

    protected $commands = [
        \App\Console\Commands\BackupDatabase::class
    ];

  
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('db:backup')->twiceDaily(12, 24); //每天12点和24点执行任务
    }

使用Cron定时调度

命令行

[root@localhost /]   crontab -e

添加如下代码

* * * * * /usr/bin/php /www-data/xxxx/artisan schedule:run 1>> /dev/null 2>&1

查看已有的任务调度

[root@localhost /]  crontab -u root -l

over

你可能感兴趣的:(Laravel定时任务备份数据库)