DaqClientConfigService.cs
2.94 KB
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
using CNCFanucDataReading;
using FreeSql;
using FreeSql.Internal;
using System;
using System.Threading.Tasks;
namespace CNCFanucDataReading
{
public class DaqClientConfigService : IDisposable
{
private readonly IFreeSql _fsql;
private bool _disposed = false;
public DaqClientConfigService(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
throw new ArgumentException("数据库连接字符串不能为空", nameof(connectionString));
_fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, connectionString)
.UseAutoSyncStructure(false) // 自动同步实体结构到数据库
.Build();
}
/// <summary>
/// 每隔5秒更新客户端最后在线时间
/// </summary>
public async Task UpdateHeartbeatAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
// 更新客户端最后在线时间
await UpdateClientLastSeenAsync();
// 设置间隔时间
await Task.Delay(AppConfig.DAQClientInterval, cancellationToken);
}
catch (TaskCanceledException)
{
break;
}
catch (Exception ex)
{
Console.WriteLine($"更新心跳失败: {ex.Message}");
// 出错后等待一段时间重试
try
{
await Task.Delay(10000, cancellationToken);
}
catch (TaskCanceledException)
{
break;
}
}
}
Console.WriteLine("心跳更新任务已停止");
}
/// <summary>
/// 更新客户端最后在线时间
/// </summary>
private async Task UpdateClientLastSeenAsync()
{
try
{
var id = Guid.Parse(AppConfig.DaqClientId);
var result = await _fsql.Update<DaqClientConfig>()
.Set(a => a.LastSeenDate, DateTime.Now)
.Where(a => a.Id == id)
.ExecuteAffrowsAsync();
if (result > 0)
{
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 客户端心跳更新成功");
}
}
catch (Exception ex)
{
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 更新心跳失败: {ex.Message}");
}
}
public void Dispose()
{
if (!_disposed)
{
_fsql?.Dispose();
_disposed = true;
}
}
}
}