laravel添加日常备份任务

app/Console/Command/MySqlDump.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

//mysql每天备份, 需要在crontab -e添加以下命令
//* * * * * /usr/local/php/bin/php /wwwroot/shells/artisan schedule:run >> /dev/null 2>&1
class MySqlDump extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mysqldump';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '项目数据库每天备份任务';


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $ds = DIRECTORY_SEPARATOR;

        $schema = env('DB_DATABASE');
        $user = env('DB_USERNAME');
        $password = env('DB_PASSWORD');
        $path = database_path() . $ds . 'backups' . $ds . date('Y-m') . $ds;
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }

        $file = date('Y-m-d') . '.sql';
        $command = sprintf('/usr/local/mysql/bin/mysqldump %s -u %s -p\'%s\' > %s', $schema, $user, $password, $path . $file);

        exec($command);
    }
}

app/Console/Kernel.php

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //\App\Console\Commands\MakeCourseKeyword::class,
        \App\Console\Commands\MySqlDump::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
//        $schedule->command('MakeCourseKeyword')
//                 ->dailyAt("03:00")
//                 ->sendOutputTo('storage/logs/MakeCourseKeyword.log', true);
        $schedule->command('mysqldump')
            ->dailyAt('03:00');
    }
}

 

posted @ 2016-12-30 15:14  佚名000  阅读(449)  评论(0)    收藏  举报