C# 实现每日定时任务(比如每天8点),优雅的实现
C# 中可以使用 Timer 类来实现每日定时任务。以下是一个示例代码:
using System;
using System.Timers;
class Program
{
static void Main(string[] args)
{
// 设置定时器
Timer timer = new Timer();
timer.Interval = TimeSpan.FromHours(24).TotalMilliseconds; // 24小时
timer.Elapsed += Timer_Elapsed;
// 计算下一次触发时间,并启动定时器
DateTime now = DateTime.Now;
DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 8, 0, 0); // 每天8点
if (nextRunTime < now)
{
nextRunTime = nextRunTime.AddDays(1);
}
TimeSpan timeToNextRun = nextRunTime - now;
timer.Start();
Console.WriteLine($"下次执行时间:{nextRunTime}");
// 等待定时器启动
Console.ReadLine();
}
private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
// 处理定时任务
Console.WriteLine($"执行时间:{DateTime.Now}");
// 计算下一次触发时间,并重新启动定时器
DateTime now = DateTime.Now;
DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 8, 0, 0); // 每天8点
if (nextRunTime < now)
{
nextRunTime = nextRunTime.AddDays(1);
}
TimeSpan timeToNextRun = nextRunTime - now;
((Timer)sender).Interval = timeToNextRun.TotalMilliseconds;
((Timer)sender).Start();
Console.WriteLine($"下次执行时间:{nextRunTime}");
}
}
在代码中,首先创建一个 Timer 对象,并设置其间隔为 24 小时。然后计算下一次要执行任务的时间,并启动定时器。在定时器的 Elapsed 事件中,处理定时任务后,重新计算下一次要执行任务的时间,并重新启动定时器。这样,就可以每天在固定的时间执行任务了。
原文地址: https://www.cveoy.top/t/topic/BDQ 著作权归作者所有。请勿转载和采集!