我认为这将做的工作适合你:
static void Main(string[] args)
{
StartTimer(TimeSpan.FromMinutes(20.0), "TimerA", true);
StartTimer(TimeSpan.FromMinutes(30.0), "TimerB", true);
StartTimer(TimeSpan.FromMinutes(45.0), "TimerC", true);
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
启动定时器功能启动定时器,并返回它(如果你需要参考)。这里的关键是你给它定时器名称,并告诉它是否要将定时器对准整个小时。如果你不想对准整个小时,那么定时器将立即以指定的频率启动。
public static Timer StartTimer(TimeSpan frequency, string timerName, bool alignToHour)
{
if (alignToHour)
{
return new Timer(OnTimerTick, timerName, ComputeDelay(frequency), frequency);
}
else
{
return new Timer(OnTimerTick, timerName, TimeSpan.Zero, frequency);
}
}
当计时器滴答时将被触发的函数。
public static void OnTimerTick(object state)
{
Console.WriteLine((string)state + " " + DateTime.Now.ToString("H:mm"));
}
此方法计算如果定时器必须在整小时对齐时所需的延迟。它只适用于频率小于1小时或超过1分钟的情况。
public static TimeSpan ComputeDelay(TimeSpan frequency)
{
if (frequency > TimeSpan.FromHours(1.0) ||
frequency < TimeSpan.FromMinutes(1.0))
{
throw new ArgumentException(
"The frequency cannot be more than one hour or less than one minute!");
}
return frequency - TimeSpan.FromMinutes(DateTime.Now.Minute % frequency.Minutes);
}
注:在您的示例运行在1小时频率45分钟计时器,但你上20次分钟和30分钟的频率(分别)运行20倍分钟和30分钟的定时器。我的代码在1小时的频率上无法使用45分钟的定时器,但它在各自的频率上使用20,30和45分钟的定时器。我不确定你的例子是否错误,但如果没有错,那么我认为你应该能够弄清楚如何从这里处理这种差异。
你能解释一下你想做什么吗? –
@Snowy,你在用什么编程语言? 。净?此外,在你的例子中,计时器C每小时执行一次,而不是每45分钟执行一次......那是你真正想要的吗? – Kiril
只使用一个计时器,以便它们永远不会分开。将其设置为下一个到期间隔,然后梳理需要完成的工作。总是从时钟计算时间间隔,不要增加一个增量,因为它总是会漂移很晚。 –