对于长时间等待(24 小时或更长),使用什么计时器才是正确的?
简单等待 24 小时 +/- 1 秒的最佳方法是什么?我知道长时间的 Threading.Sleep 并不准确,并且可能会根据 CPU 负载而变化。
我看到 System.Timers.Timer 允许您创建定时事件。我如何使用它来简单地等待 24 小时?
private void myTest{
// SET SOMETHING UP
m_theTimer = new System.Timers.Timer();
m_theTimer.Elapsed += new ElapsedEventHandler(OurTimerCallback);
const int hrsToMs = 60 * 60 * 1000;
m_theTimer.Interval = TestPeriodHours * hrsToMs;
m_theTimer.Enabled = true;
//---->want to wait for 24 hours<------
// RESUME TEST HERE
VerifySomething()
}
public void OurTimerCallback(object source, ElapsedEventArgs e)
{
Console.WriteLine("Received a callback, the time is {0}", e.SignalTime);
}
What is the best way to simply wait for 24 hours +/- 1 second. I know that Threading.Sleep for a long time is not accurate and can vary based on the CPU loads.
I see the System.Timers.Timer allows you to create a timed event. How do I use this to simply wait for 24 hours?
private void myTest{
// SET SOMETHING UP
m_theTimer = new System.Timers.Timer();
m_theTimer.Elapsed += new ElapsedEventHandler(OurTimerCallback);
const int hrsToMs = 60 * 60 * 1000;
m_theTimer.Interval = TestPeriodHours * hrsToMs;
m_theTimer.Enabled = true;
//---->want to wait for 24 hours<------
// RESUME TEST HERE
VerifySomething()
}
public void OurTimerCallback(object source, ElapsedEventArgs e)
{
Console.WriteLine("Received a callback, the time is {0}", e.SignalTime);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也许 Quartz.NET 就是您正在寻找的。 http://quartznet.sourceforge.net/。
Maybe Quartz.NET is what you are looking for. http://quartznet.sourceforge.net/.
+/- 1 秒?我会使用混合方法。
使用任务调度程序启动一个程序,时间为 23:58。然后让该程序休眠 2 分钟或更短时间,直到确切的时刻到来,然后执行工作。
如果你不关心 1 秒的精度,你可以单独使用任务调度程序,按 24 小时划分。
+/- 1 second? I would use a hybrid approach.
Use task scheduler to start a program, in 23:58. Then have that program sleep for 2 minutes or less until the exact moment arrives, then perform the work.
If you don't care about the 1 second accuracy, you could just use task scheduler alone, on the 24 hour division.
假设您处于胜利状态。
声明一个日期时间变量并在 form_load 事件上分配一个值。
创建一个计时器并每秒触发该事件。
检查计时器事件中的日期时间变量。如果时间跨度为 1 小时,则调用您的 main 方法。
Assuming you are on win forms.
Declare a datetime variable and assign a value on form_load event.
Create a timer and fire the the event in every second.
Check the datetime variable in the timer event. if timespan is 1 hour, call your main method.
我认为您可以结合使用 ManualResetEvent 以及计时器。
I think you can use a combination of ManualResetEvent along with Timer.
如果您确实想使用计时器,也许这更好。
但我有点模糊为什么 ManuelResetEvent 不能更轻松地完成这项工作......
Maybe this is better if you really want to use a timer.
But I'm a little fuzzy on why ManuelResetEvent doesn't do the job easier....