feat(timer): 新增配置同步到数据库及主节点选举

T5: TimerServiceBase.syncConfigToDatabase() - syncs task config to DB
T6: HostServiceBase - auto master election, stale node detection,
    getMasterNode/setMasterNode methods
This commit is contained in:
augushong
2026-05-26 02:33:43 +08:00
parent d719a99d14
commit abeac2c3cb
5 changed files with 124 additions and 0 deletions

View File

@@ -2,12 +2,69 @@
namespace base\common\service;
use app\admin\model\SystemTimerConfig;
use app\common\model\VirtualModel;
class TimerServiceBase
{
protected $taskList = null;
/**
* 将配置文件中的定时任务同步到数据库.
* 仅新增不存在的记录,标记孤立记录,不覆盖 run_type/status.
*/
public static function syncConfigToDatabase(): void
{
$config_list = include app_file_path('common/command/timer/config.php');
// 提取唯一的任务名称(并发扩展会产生同名配置,需去重)
$config_names = [];
foreach ($config_list as $config_item) {
$item = static::initConfigItem($config_item);
$name = (string) $item['name'];
if ($name !== '' && !in_array($name, $config_names, true)) {
$config_names[] = $name;
}
}
// 查询已有记录
$existing = SystemTimerConfig::column('task_name');
$now = time();
// 新增:配置中有但数据库中没有的
$new_names = array_diff($config_names, $existing);
foreach ($new_names as $name) {
SystemTimerConfig::create([
'task_name' => $name,
'run_type' => 'auto',
'status' => 1,
'is_synced' => 1,
'create_time' => $now,
'update_time' => $now,
]);
}
// 已存在且仍在配置中:仅更新 is_synced=1不动 run_type/status
$still_exists = array_intersect($existing, $config_names);
foreach ($still_exists as $name) {
SystemTimerConfig::where('task_name', $name)
->update([
'is_synced' => 1,
'update_time' => $now,
]);
}
// 已存在但不在配置中:标记为孤立
$orphaned = array_diff($existing, $config_names);
foreach ($orphaned as $name) {
SystemTimerConfig::where('task_name', $name)
->update([
'is_synced' => 0,
'update_time' => $now,
]);
}
}
public static function generateAllTaskInstanceList()
{
$config_list = include app_file_path('common/command/timer/config.php');