我有一个.Net核心6项目,我想安排一些每天上午9点工作的任务。
任务调度程序的最佳方式是什么?
注意: Hangfire是一个很好的解决方案,但是它与DataBase一起工作,这对我的项目是不好的。
发布于 2022-05-25 07:41:54
您可以使用定时器。
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);
}每次我们安排一个作业,而不是有一个24小时的计时器时,创建一个新计时器的原因再次是夏令节约。在夏季到冬季或相反的日子里,上午9点和第二天早上9点之间的差别不是24小时。
发布于 2022-06-04 14:29:30
NET 6支持反复出现的任务,您可以很容易地构建一个windows服务。将其构建为windows服务意味着一旦安装了它,就不必担心重新启动,因为您可以告诉服务在重新启动时启动。
结帐使用BackgroundService创建Windows
你的总阅读时间大约是20分钟,所以它是相当直接的。在堆栈溢出的回答中解释起来有点过于复杂了。
https://stackoverflow.com/questions/72373372
复制相似问题