-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskSchedulerService.cs
More file actions
34 lines (28 loc) · 949 Bytes
/
TaskSchedulerService.cs
File metadata and controls
34 lines (28 loc) · 949 Bytes
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
namespace StromAPI;
public class TaskSchedulerService
{
private readonly Func<Task> _taskToExecuteAsync;
private readonly TimeSpan _executionTime;
private Timer? _timer;
public TaskSchedulerService(Func<Task> taskToExecuteAsync, TimeSpan executionTime)
{
_taskToExecuteAsync = taskToExecuteAsync;
_executionTime = executionTime;
}
public void ScheduleNextExecution()
{
DateTime now = DateTime.Now;
DateTime nextExecutionTime = now.Date.Add(_executionTime);
if (nextExecutionTime < now)
{
nextExecutionTime = nextExecutionTime.AddDays(1);
}
double interval = (nextExecutionTime - now).TotalMilliseconds;
_timer = new Timer(ExecuteTaskAsync, null, (int)interval, Timeout.Infinite);
}
private async void ExecuteTaskAsync(object state)
{
await _taskToExecuteAsync();
ScheduleNextExecution();
}
}