-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimedHostedService.cs
74 lines (58 loc) · 2.18 KB
/
TimedHostedService.cs
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
using BackGroundServiceTest;
using Microsoft.Extensions.Options;
public class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger<TimedHostedService> _logger;
private Timer? _timer = null;
private readonly ScheduleConfig _scheduleConfig;
public TimedHostedService(
ILogger<TimedHostedService> logger,
IOptions<ScheduleConfig> scheduleConfig)
{
_logger = logger;
_scheduleConfig = scheduleConfig.Value;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
ScheduleDailyTaskBasedOnUserSpecifiedTime();
return Task.CompletedTask;
}
private void ScheduleDailyTaskBasedOnUserSpecifiedTime()
{
var currentTime = DateTime.UtcNow;
TimeZoneInfo userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(_scheduleConfig.TimeZoneId);
var currentTimeInUserTimeZone = TimeZoneInfo.ConvertTimeFromUtc(currentTime, userTimeZone);
var targetTime = new DateTime(
currentTimeInUserTimeZone.Year,
currentTimeInUserTimeZone.Month,
currentTimeInUserTimeZone.Day,
_scheduleConfig.Hour,
_scheduleConfig.Minute,
0,
DateTimeKind.Unspecified);
if (currentTimeInUserTimeZone > targetTime)
{
targetTime = targetTime.AddDays(1);
}
targetTime = TimeZoneInfo.ConvertTimeToUtc(targetTime, userTimeZone);
var timeToWait = targetTime - currentTime;
_timer = new Timer(DoWork, null, timeToWait, TimeSpan.FromDays(1));
}
private void DoWork(object? state)
{
_logger.LogInformation("Timed Hosted Service is working.");
// Reschedule the next run
ScheduleDailyTaskBasedOnUserSpecifiedTime();
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}