-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTaskTodayCheckerService.cs
61 lines (51 loc) · 1.99 KB
/
TaskTodayCheckerService.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
using TasksWebApp.Models;
namespace TasksWebApp;
/// <summary>
/// Сервіс, який перевірятиме кожне завдання кодну добу, чи відображати його сьогодні.
/// </summary>
public class TaskTodayCheckerService
{
private Timer? timer;
public TaskTodayCheckerService() { }
public void Start()
{
/*// Calculate time until the first run (immediate) and set the period to 10 seconds
TimeSpan timeUntilFirstRun = TimeSpan.Zero;
TimeSpan period = TimeSpan.FromSeconds(10);
// Set up the timer to run the method every 10 seconds
timer = new Timer(new TimerCallback(state => DoDailyTask(state!)), null, timeUntilFirstRun, period);*/
// Calculate the time until the next midnight
DateTime now = DateTime.Now;
DateTime nextMidnight = now.Date.AddDays(1); // Next day at 00:00:00
TimeSpan timeUntilMidnight = nextMidnight - now;
// Set up the timer to run the method every day at midnight
timer = new Timer(new TimerCallback(state => DoDailyTask(state!)), null, timeUntilMidnight, TimeSpan.FromDays(1));
}
private void DoDailyTask(object state)
{
try
{
ApplicationContext db = new ApplicationContext();
List<UserTask> tasks = db.Tasks.ToList();
int countTaskToday = 0;
foreach(var task in tasks)
{
if (task.FinishDate?.Date == DateTime.Now.Date)
{
task.Today = true;
countTaskToday++;
}
else
{
task.Today = false;
}
}
db.SaveChanges();
Console.WriteLine($"Сьогодні буде відображено {countTaskToday} з {tasks.Count}");
}
catch (Exception ex)
{
Console.WriteLine($"Виникла помилка: {ex.Message}");
}
}
}