zhaolei
9 days ago 921de2254ff5712a44ed8575ee8efe34252f6603
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
 
namespace Prow.Tasks
{
    /// <summary>
    /// Trigger 触发器进程类 负责维护触发器的运行
    /// </summary>
    internal class TriggerProcess
    {
        /// <summary>
        /// 触发器取消令牌 此令牌单独设置触发器是否工作
        /// </summary>
        private CancellationTokenSource? _triggerCancelTokenSource;
 
        /// <summary>
        /// 调度取消令牌
        /// </summary>
        private CancellationToken _schedulerCancelToken;
 
        /// <summary>
        /// 触发器取消令牌与调度取消令牌合集
        /// </summary>
        private CancellationTokenSource? _cancelTokenSource;
 
        /// <summary>
        /// 获得 任务调度名称
        /// </summary>
        public string Name { get; set; }
 
        /// <summary>
        /// 获得/设置 触发器实例
        /// </summary>
        public ITrigger Trigger { get; set; }
 
        /// <summary>
        /// 执行任务方法
        /// </summary>
        public Func<CancellationToken, Task> DoWork { get; set; }
 
        /// <summary>
        /// 获得/设置 日志委托
        /// </summary>
        public Action<string> LoggerAction { get; set; }
 
        /// <summary>
        /// 获得/设置 触发器持久化 IStorage 实例
        /// </summary>
        public IStorage Storage { get; set; }
 
        /// <summary>
        /// 构造函数
        /// </summary>
        public TriggerProcess(string name, Action<string> loggerAction, ITrigger trigger, IStorage storage, Func<CancellationToken, Task> dowork)
        {
            Name = name;
            LoggerAction = loggerAction;
            Trigger = trigger;
            Storage = storage;
            DoWork = dowork;
        }
 
        /// <summary>
        /// 触发器处理器开始工作
        /// </summary>
        /// <param name="cancellationToken">调度取消令牌</param>
        public void Start(CancellationToken? cancellationToken)
        {
            _schedulerCancelToken = cancellationToken ?? CancellationToken.None;
            _triggerCancelTokenSource = new CancellationTokenSource();
            _cancelTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_triggerCancelTokenSource.Token, _schedulerCancelToken);
 
            // Load storage
            Trigger.Load(Name, Storage, LoggerAction);
 
            // 异步执行触发器开始心跳
            Task.Run(async () =>
            {
                // 等待开始时间
                if (Trigger.StartTime != null)
                {
                    var interval = Trigger.StartTime.Value - DateTime.Now;
                    if (interval > TimeSpan.Zero) _cancelTokenSource.Token.WaitHandle.WaitOne(interval);
                }
                while (!_cancelTokenSource.IsCancellationRequested)
                {
                    if (!Trigger.Pulse(_cancelTokenSource.Token)) break;
 
                    LoggerAction($"{Trigger.GetType().Name} PulseAsync() Trigger.Enabled({Trigger.Enabled}) Cancelled({_cancelTokenSource.IsCancellationRequested})");
 
                    // 立刻运行一次
                    var sw = Stopwatch.StartNew();
                    await DoWork(_cancelTokenSource.Token).ConfigureAwait(false);
                    sw.Stop();
                    Trigger.LastRunElapsedTime = sw.Elapsed;
                    Trigger.PulseCallback?.Invoke(Trigger);
                    LoggerAction($"{Trigger.GetType().Name} {nameof(DoWork)}({Trigger.LastResult}) Elapsed: {Trigger.LastRunElapsedTime} NextRuntime: {Trigger.NextRuntime}");
                    if (Trigger.NextRuntime == null) break;
                }
                Trigger.Save(Name, Storage, LoggerAction);
            });
        }
 
        /// <summary>
        /// 触发器停止操作
        /// </summary>
        public void Stop()
        {
            _triggerCancelTokenSource?.Cancel();
            LoggerAction($"{nameof(TriggerProcess)} Stop() called");
        }
    }
}