dnsmgr/app/command/Dmtask.php
coolxitech 638ab7cf3f refactor(command): 重构命令行任务处理逻辑
- 使用模型替换 Db::name() 方法,提高代码可读性和可维护性
- 优化 Dmtask 和 Opiptask 命令的执行逻辑
- 更新异常捕获方式,使用更具体的异常类
- 调整命名空间和引入的类,以适应新的代码结构
2024-11-09 20:23:57 +08:00

89 lines
2.6 KiB
PHP

<?php
declare (strict_types=1);
namespace app\command;
use Co;
use Exception;
use Swoole\ExitException;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use app\model\Config as ConfigModel;
use app\model\Dmtask as DmtaskModel;
use think\facade\Config;
use app\lib\TaskRunner;
use function Co\run;
use function go;
class Dmtask extends Command
{
protected function configure()
{
// 指令配置
$this->setName('dmtask')
->setDescription('容灾切换任务');
}
protected function execute(Input $input, Output $output)
{
$res = ConfigModel::cache('configs', 0)->column('value', 'key');
Config::set($res, 'sys');
config_set('run_error', '');
if (!extension_loaded('swoole')) {
$output->writeln('[Error] 未安装Swoole扩展');
config_set('run_error', '未安装Swoole扩展');
return;
}
try {
$output->writeln('进程启动成功.');
$this->runtask();
} catch (Exception $e) {
$output->writeln('[Error] '.$e->getMessage());
config_set('run_error', $e->getMessage());
}
}
private function runtask()
{
Co::set(['hook_flags' => SWOOLE_HOOK_ALL]);
run(function () {
$date = date("Ymd");
$count = config_get('run_count', null, true) ?? 0;
while (true) {
sleep(1);
if ($date != date("Ymd")) {
$count = 0;
$date = date("Ymd");
}
$rows = DmtaskModel::where('checknexttime', '<=', time())->where('active', 1)->order('id', 'ASC')->select();
foreach ($rows as $row) {
go(function () use ($row) {
try {
(new TaskRunner())->execute($row);
} catch (ExitException $e) {
echo $e->getStatus()."\n";
} catch (Exception $e) {
echo $e->__toString()."\n";
}
});
DmtaskModel::where('id', $row['id'])->update([
'checktime' => time(),
'checknexttime' => time() + $row['frequency'],
]);
$count++;
}
config_set('run_time', date("Y-m-d H:i:s"));
config_set('run_count', $count);
}
});
}
}