# 任务调度篇
TIP
laravel手册有详细的介绍,这里只是基于laravel做的快速使用示例.
Laravel 的命令行调度器允许在 Laravel 中清晰明了地定义命令调度。在使用这个任务调度器时,只需要在服务器上创建单个 Cron 入口。任务调度在 app/Console/Kernel.php 的 schedule 方法中进行定义.
# 前提
TIP
组件包修改好的app/Console/Kernel.php
代码如下:
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Console\Commands\LaravelFastApi\V1\ExecuteTotalCommand;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
//数据库备份
$this->mysqlBak($schedule);
//测试用
//$schedule->command(ExecuteTotalCommand::class)->everyThreeMinutes();
// $schedule->command(ExecuteTotalCommand::class)->dailyAt('5:00');
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
/**
* 数据库备份
*
* @param Schedule $schedule
* @return void
*/
public function mysqlBak(Schedule $schedule)
{
//测试用 每三分钟
//$schedule->exec('source 绝对路径/cron/mysql_bak.sh')->everyThreeMinutes()->timezone('Asia/Shanghai');
//每天凌晨零点40执行数据库备份
// $schedule->exec('source 绝对路径/cron/mysql_bak.sh')->dailyAt('00:40')->timezone('Asia/Shanghai');
}
}
# 启动调度器
path-to-your-project
项目部署的绝对路径
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
# 示例:
项目目录:
/www/wwwroot/youhujun.com/api.youhujun.com
执行
crontab -e
将如下内容添加进去
* * * * * cd /www/wwwroot/youhujun.com/api.youhujun.com && php artisan schedule:run >> /dev/null 2>&1
# 配置数据库备份
组件包发布成功以后在\cron\mysql_bal.sh.example
预留了mysql数据库备份脚本
cp mysql_bal.sh.example mysql_bal.sh
根据自己的项目配置自行调整,配置好以后,自行调试代码
# /bin/sh
time=$(date "+%Y%m%d%H%M%S")
mysqldump -u用户名 -p密码% 数据库名 > 路径/数据库名$time.sql
# 调试统计命令
根据app/Console/Kernel.php
中代码可以看出,组件包已经预置了App\Console\Commands\LaravelFastApi\V1\ExecuteTotalCommand
执行统计的命令
内容如下:
<?php
namespace App\Console\Commands\LaravelFastApi\V1;
use Illuminate\Console\Command;
use App\Facade\Common\V1\Total\TotalAllDataFacade;
class ExecuteTotalCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'execute:total';
/**
* The console command description.
*
* @var string
*/
protected $description = 'implement data statistics';
/**
* Execute the console command.
*/
public function handle()
{
//执行所有统计
TotalAllDataFacade::doAllTotal();
}
}
可以看出App\Facade\Common\V1\Total\TotalAllDataFacade
是一个统计门面,
也就是说实际后续业务中有其他的计划任务执行统计需要,都可以封装相应统计门面在这里执行