pengmn
2025-05-30 cd40ada4efe0d0a4036714cf597ce170b8cf5a54
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
using HH.WCS.HangYang.api;
using HH.WCS.HangYang.core;
using HH.WCS.HangYang.device;
using HH.WCS.HangYang.process;
using HH.WCS.HangYang.util;
using HH.WCS.HangYang.wms;
using Microsoft.Owin.Hosting;
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Topshelf;
using Monitor = HH.WCS.HangYang.core.Monitor;
 
namespace HH.WCS.HangYang
{
    internal class Program
    {
        static void Main(string[] args)
        {
 
 
            Settings.Init();
            //1.0 开启api
            Startup();
            //2.0 开启tcp
            StartTcp();
            //3.0 开启线程
            var rc = HostFactory.Run(x =>
            {
                using (var worker = new WorkThread())
                {
                    worker.Start();
 
                    // 主线程等待退出信号
                    Console.CancelKeyPress += (s, e) => worker.Stop();
                    Thread.Sleep(Timeout.Infinite);
                }
                x.RunAsLocalSystem();
 
                x.SetDescription("hh123");
                x.SetDisplayName("hh123.wms");
                x.SetServiceName("hh123.wms");
            });
 
            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
            Environment.ExitCode = exitCode;
        }
 
        private static void Startup()
        {
            Console.WriteLine("Startup ApiController");
            Task.Run(() =>
            {
                //var url = "http://192.168.1.87:8901";//{SettingHelper.port}
                var url = $"http://+:{Settings.port}";//
                Console.WriteLine(url);
                using (WebApp.Start<Startup>(url))
                {
                    Console.WriteLine("Running on {0}", url);
                    Console.ReadLine();
                }
            });
        }
        private static void StartTcp()
        {
            //new TcpServer("192.168.1.87");
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    Console.WriteLine($"ip= {ip.ToString()}");
                    new TcpServer(ip.ToString());
                }
            }
        }
 
 
        public class WorkThread : IDisposable
        {
            private readonly List<Task> _tasks = new List<Task>();
            private readonly CancellationTokenSource _cts = new CancellationTokenSource();
            private bool _disposed;
 
            private readonly Dictionary<string, Action> _taskRegistry = new Dictionary<string, Action>
            {
                {"循环作业创建任务", WCSCore.ExecuteJob},
                {"循环入库暂存区生成入库任务", WCSCore.ProcessZoneInventoryCycle},
                {"根据配盘单生成出库任务", WCSCore.GenerateFromPicking},
            };
 
 
            private readonly List<(string Name, Action Action, Task Task)> _taskInfoList = new List<(string, Action, Task)>();
 
            public void Start()
            {
 
                // 创建所有任务
                foreach (var task in _taskRegistry)
                {
                    var managedTask = CreateManagedTask(task.Value, task.Key, _cts.Token);
                    _taskInfoList.Add((task.Key, task.Value, managedTask));
                    _tasks.Add(managedTask);
                }
 
                // 启动健康监控
                _tasks.Add(StartHealthMonitor());
 
                LogHelper.Info($"工作线程已启动,共 {_tasks.Count} 个任务");
 
            }
            public void Stop()
            {
                if (_cts.IsCancellationRequested) return;
 
                LogHelper.Info("正在停止工作线程...");
                _cts.Cancel();
 
                Task.WhenAll(_tasks)
                    .ContinueWith(t =>
                    {
                        _tasks.Clear();
                        LogHelper.Info("所有工作线程已停止");
                    });
            }
            private Task CreateManagedTask(Action action, string taskName, CancellationToken ct)
            {
                int retryCount = 0;
 
                return Task.Run(async () =>
                {
                    LogHelper.Info($"任务 [{taskName}] 启动");
 
                    while (!ct.IsCancellationRequested)
                    {
                        try
                        {
                            var stopwatch = Stopwatch.StartNew();
                            action();
                            stopwatch.Stop();
 
                            if (stopwatch.ElapsedMilliseconds > 10000)
                            {
                                LogHelper.Info($"任务 [{taskName}] 执行时间过长: {stopwatch.ElapsedMilliseconds}ms");
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            LogHelper.Info($"任务 [{taskName}] 已取消");
                            break;
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error($"任务 [{taskName}] 执行失败: {ex.Message}", ex);
                            var delay = Math.Min(30000, 1000 * (int)Math.Pow(2, retryCount));
                            await Task.Delay(delay, ct);
                            retryCount++;
                        }
 
                        await Task.Delay(3000, ct);
                    }
 
                    LogHelper.Info($"任务 [{taskName}] 已退出");
                }, ct);
            }
            public void Dispose()
            {
                if (_disposed) return;
 
                Stop();
                _cts.Dispose();
                _disposed = true;
                GC.SuppressFinalize(this);
            }
 
            private Task StartHealthMonitor()
            {
                return Task.Run(async () =>
                {
                    while (!_cts.IsCancellationRequested)
                    {
                        var faultedTasks = _taskInfoList.Where(x => x.Task.IsFaulted).ToList();
                        foreach (var (name, action, task) in faultedTasks)
                        {
                            LogHelper.Info($"检测到失败任务: {name}");
 
                            // 移除旧任务
                            _taskInfoList.Remove((name, action, task));
                            _tasks.Remove(task);
 
                            // 创建新任务
                            var newTask = CreateManagedTask(action, name, _cts.Token);
                            _taskInfoList.Add((name, action, newTask));
                            _tasks.Add(newTask);
                        }
 
                        await Task.Delay(10000, _cts.Token);
                    }
                }, _cts.Token);
            }
 
        }
    }
}