C# 实现每日定时任务(比如每天8点),使用System.Timers
.Timer
C# 实现每日定时任务可以使用 System.Timers.Timer 类。该类可以在指定的时间间隔内定期触发事件。
以下是实现每天8点执行任务的示例代码:
using System;
using System.Timers;
class Program
{
static void Main(string[] args)
{
// 设置每天的执行时间为8点
var executeTime = new TimeSpan(8, 0, 0);
var timer = new System.Timers.Timer();
timer.Interval = 1000; // 每秒钟检查一次
timer.Elapsed += (sender, e) =>
{
// 检查当前时间是否达到执行时间
var currentTime = DateTime.Now.TimeOfDay;
if (currentTime >= executeTime && currentTime < executeTime.Add(TimeSpan.FromSeconds(timer.Interval / 1000)))
{
// 执行任务
Console.WriteLine("Task executed at {0}", DateTime.Now);
}
};
timer.Start();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
该示例中,我们设置了每天的执行时间为8点,然后使用 System.Timers.Timer 类的 Elapsed 事件来检查当前时间是否达到执行时间,如果达到,则执行任务。由于定时器的精度可能不够高,因此我们使用 Add 方法来增加一定的时间间隔,以避免在执行任务时出现时间上的误差。
需要注意的是,由于 System.Timers.Timer 类是在另一个线程上触发事件的,因此在事件处理程序中访问 UI 控件等线程敏感的资源时,需要使用 Invoke 方法来切换到 UI 线程。
原文地址: https://www.cveoy.top/t/topic/BDL 著作权归作者所有。请勿转载和采集!