Hello. I would like to ask the following question - suppose there is some kind of Windows service that is constantly running. How can we make this service perform a certain method every day at a certain time, and quietly sit in memory all the rest of the time? Thank you in advance
- oneAnd what is the Task Scheduler is not suitable? - mantigatos
- probably the fact that I had not heard of him) - sandy
- ru.wikipedia.org/wiki/Task_Scheduler - mantigatos
- Ah you about this. No, unfortunately, this is not the case, it is about writing the service and calling this service the method of the service itself or of some class - sandy
- In the service, you bet on a timer, say, to check every minute if the time is right - call the method you need. - Yaroslav Schubert
|
1 answer
It is done using a timer:
public sealed class DailyTimer : IDisposable { private readonly Timer timer; public DailyTimer(double hours, double minutes, TimerCallback callback) { timer = new Timer(callback); Change(hours, minutes); } private static void Change(DailyTimer dailyTimer, double hours, double minutes) { var currentTime = DateTime.Now; var nextAlarm = currentTime.Date.AddHours(hours).AddMinutes(minutes); if (nextAlarm < currentTime) { nextAlarm = nextAlarm.AddDays(1); } dailyTimer.timer.Change(nextAlarm.Subtract(currentTime), TimeSpan.FromDays(1)); } public void Change(double hours, double minutes) { Change(this, hours, minutes); } public void Dispose() { timer.Dispose(); } }
|