public int StartRunning() { if (!IsMaster) return int.MinValue; // 启用了服务发现的情况下, 检查是否有其他的Master存在 if (ServiceDiscovery.Instance != null) { var discover_name = ServiceDiscovery.GetDiscoverName(GetNameKey()); var task_checkstate = ServiceDiscovery.Instance.GetSchedServiceState(discover_name); Task.WaitAll(task_checkstate); var master_state = task_checkstate.Result; if (master_state != null) { Console.WriteLine($"Error : master already exist ({Prefix})."); return int.MinValue; } } //标记以Master方式运行 RunningAsMaster = true; CreateContext().RecordAlive().Wait(); var time_start = PerformStartTime.Add(Math.Ceiling((DateTime.UtcNow - PerformStartTime).TotalMilliseconds / Interval.TotalMilliseconds) * Interval); var offset_start = time_start - DateTime.UtcNow; Timer = new Timer(async t => { var ctx = CreateContext(); // 创建演出上下文 await ctx.RecordAlive(); if (!Enabled) return; await OnUpdate(ctx); if (!await ctx.SetCurrentStatus(PerformContext.Status.Started)) return; // 尝试标记开始, 如果已经开始,退出 if (!await ctx.Lock()) return; // 尝试上活锁, 如果加锁失败, 退出 try { await OnPerform(ctx); await ctx.SetCurrentStatus(PerformContext.Status.Completed); //标记完成 } catch (Exception ex) { await ctx.SetCurrentStatus(PerformContext.Status.Error); //标记错误 _logger.LogError($"Sechedule {ctx.CurrRoundKey} Error : {ex.Message}"); } finally { await ctx.Unlock(); } }, null, offset_start, Interval); return offset_start.Seconds; }
public DateTime RoundToDateTime(int round) { return PerformStartTime.Add(TimeSpan.FromMilliseconds(round * PerformSpan.TotalMilliseconds)); }