|
1 | 1 | namespace TokenPay.BgServices
|
2 | 2 | {
|
3 |
| - public abstract class BaseScheduledService : IHostedService, IDisposable |
| 3 | + public abstract class BaseScheduledService : BackgroundService |
4 | 4 | {
|
5 |
| - private readonly Timer _timer; |
6 | 5 | protected readonly string jobName;
|
7 |
| - private readonly TimeSpan _period; |
8 | 6 | protected readonly ILogger Logger;
|
| 7 | + private readonly PeriodicTimer _timer; |
9 | 8 |
|
10 | 9 | protected BaseScheduledService(string JobName, TimeSpan period, ILogger logger)
|
11 | 10 | {
|
12 | 11 | Logger = logger;
|
13 | 12 | jobName = JobName;
|
14 |
| - _period = period; |
15 |
| - _timer = new Timer(Execute, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); |
| 13 | + _timer = new PeriodicTimer(period); |
16 | 14 | }
|
17 |
| - |
18 |
| - public void Execute(object? state = null) |
| 15 | + protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
19 | 16 | {
|
20 |
| - try |
21 |
| - { |
22 |
| - |
23 |
| - ExecuteAsync().Wait(); |
24 |
| - //Logger.LogInformation("Begin execute service"); |
25 |
| - } |
26 |
| - catch (Exception ex) |
27 |
| - { |
28 |
| - Logger.LogError(ex, $"定时任务[{jobName}]执行出现错误"); |
29 |
| - } |
30 |
| - finally |
| 17 | + Logger.LogInformation("Service {JobName} is starting.", jobName); |
| 18 | + do |
31 | 19 | {
|
32 |
| - //Logger.LogInformation("Execute finished"); |
33 |
| - _timer.Change(_period, Timeout.InfiniteTimeSpan); |
34 |
| - } |
| 20 | + try |
| 21 | + { |
| 22 | + await ExecuteAsync(); |
| 23 | + } |
| 24 | + catch (Exception ex) |
| 25 | + { |
| 26 | + Logger.LogError(ex, $"定时任务[{jobName}]执行出现错误"); |
| 27 | + } |
| 28 | + } while (!stoppingToken.IsCancellationRequested && await _timer.WaitForNextTickAsync(stoppingToken)); |
35 | 29 | }
|
36 |
| - |
37 | 30 | protected abstract Task ExecuteAsync();
|
38 |
| - |
39 |
| - public virtual void Dispose() |
40 |
| - { |
41 |
| - _timer?.Dispose(); |
42 |
| - } |
43 |
| - |
44 |
| - public Task StartAsync(CancellationToken cancellationToken) |
45 |
| - { |
46 |
| - Logger.LogInformation("Service {JobName} is starting.", jobName); |
47 |
| - _timer.Change(TimeSpan.FromSeconds(3), Timeout.InfiniteTimeSpan); |
48 |
| - return Task.CompletedTask; |
49 |
| - } |
50 |
| - |
51 |
| - public Task StopAsync(CancellationToken cancellationToken) |
| 31 | + public override Task StopAsync(CancellationToken cancellationToken) |
52 | 32 | {
|
53 | 33 | Logger.LogInformation("Service {JobName} is stopping.", jobName);
|
54 |
| - |
55 |
| - _timer?.Change(Timeout.Infinite, 0); |
56 |
| - |
57 |
| - return Task.CompletedTask; |
| 34 | + _timer.Dispose(); |
| 35 | + return base.StopAsync(cancellationToken); |
58 | 36 | }
|
59 | 37 | }
|
60 | 38 | }
|
0 commit comments