I have a .Net Core 6 project and I want do schedule some task working at every day 09:00 am.
What is the best way for task scheduler?
Note: Hangfire is good solution but it is working with DataBase, this is bad for my project.
I have a .Net Core 6 project and I want do schedule some task working at every day 09:00 am.
What is the best way for task scheduler?
Note: Hangfire is good solution but it is working with DataBase, this is bad for my project.
You can work with timers.
static DateTime GetNextRunTime()
{
DateTime now = DateTime.Now;
if (now.Hour < 9)
{
// If time of the day is before 9:00 am, then job will run today at 9
// Using this way instead of DateTime.Today.AddHours(9) because it can cause weird issues with Daylight Saving when time offset changes
return new DateTime(now.Year, now.Month, now.Day, 9, 0, 0);
}
// Job will run tommorow at 9:00
DateTime tomorrow = DateTime.Today.AddDays(1);
return new DateTime(tomorrow .Year, tomorrow .Month, tomorrow .Day, 9, 0, 0);
}
static void ScheduleNextJob(Action action)
{
var dueTime = GetNextRunTime() - DateTime.Now;
System.Threading.Timer timer = null;
timer = new Timer(() =>
{
// run your code
try
{
action();
}
catch
{
// Handle the exception here, but make sure next job is scheduled if an exception is thrown by your code.
}
ScheduleNextJob(action); // Schedule next job
timer?.Dispose(); // Dispose the timer for the current job
}, null, dueTime, TimeSpan.Infinite);
}
The reason for creating a new timer everytime we schedule a job rather than have a timer with 24 hours period is again Daylight saving. On days the time changes from summer to winter or vice versa, the difference between 9am and 9am next day is not 24 hours.
NET 6 has built in support for recurring tasks and you can build a windows service pretty easily. Building this as a windows service means that once you've installed it you don't have to worry about a reboot because you can tell the service to start on reboot.
Checkout Create a Windows Service using BackgroundService
Your total reading time would be about 20 minutes, so it is pretty straight forward. It is a bit too involved to explain fully in a Stack Overflow answer.