using System;
using System.Timers;
class Program
{
static Timer timer;
static void Main(string[] args)
{
// 设置定时器,每天的特定时间执行操作
timer = new Timer();
timer.Interval = CalculateIntervalToNextExecutionTime(new TimeSpan(14, 0, 0)); // 每天14:00执行
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
Console.WriteLine("等待定时任务触发...");
Console.ReadLine();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("定时任务执行于: " + DateTime.Now);
// 在这里编写你想要定时执行的操作代码
// 例如:调用方法、发送邮件等
}
private static double CalculateIntervalToNextExecutionTime(TimeSpan executionTime)
{
DateTime now = DateTime.Now;
DateTime todayExecution = now.Date + executionTime;
if (now >= todayExecution)
{
todayExecution = todayExecution.AddDays(1);
}
return (todayExecution - now).TotalMilliseconds;
}
}
System.Timers.Timer 类来创建一个定时器。定时器会在指定的时间间隔后触发事件。true,表示定时器会在每次触发后自动重置,以便每天同一时间再次触发。通过这种方式,你可以实现每天在指定时间执行某些操作。
上一篇:c# 等待多少秒写法
下一篇:c# 写文本文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站