C# 实现每日定时任务,使用System.Timers
.Timer
System.Timers.Timer类是C#中用于定时任务的一种常用方式。它允许我们设置一个定时器并在指定的时间间隔内执行某些代码。
下面是一个简单的示例:
using System;
using System.Timers;
namespace TimerExample
{
class Program
{
static void Main(string[] args)
{
// 创建一个计时器,并设置时间间隔为一天
var timer = new System.Timers.Timer();
timer.Interval = 24 * 60 * 60 * 1000;
// 绑定事件处理程序
timer.Elapsed += OnTimedEvent;
// 启动计时器
timer.Enabled = true;
// 等待用户输入以退出程序
Console.WriteLine("Press any key to exit the program...");
Console.ReadKey();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
// 在这里写下每日需要执行的代码
Console.WriteLine("The daily task has been executed at {0}", e.SignalTime);
}
}
}
在上面的示例中,我们创建了一个计时器,并设置了它的时间间隔为一天。然后,我们绑定了一个事件处理程序OnTimedEvent,它将在计时器到期时执行。在OnTimedEvent中,我们可以写下我们需要每日执行的代码。
最后,我们启动计时器并等待用户输入以退出程序。
原文地址: https://www.cveoy.top/t/topic/BDJ 著作权归作者所有。请勿转载和采集!