[英]C# equivalent of Java's timer.scheduleAtFixedRate
我需要一种每5分钟准确运行一次的方法。 我不能使用Timer,因为我注意到它会慢慢变得不同步(即最终将在00:01、00:06、00:11、00:16等运行)。
尽管它需要准确,但我并不需要太精确。 每5分钟+/- 1秒就可以了,只要经过几天的跑步,它仍然会准确地在5分钟标记上滴答。
到目前为止,我想到的是创建一个间隔为1秒的计时器,该计时器会不断检查DateTime.Now,以查看下一个5分钟标记是否已过去。 我想知道C#库中是否有更优雅的解决方案或我错过的东西。
编辑:我现在有以下模板,它可以满足我的要求。
public class ThreadTest
{
private Thread thread;
private long nextExecutionTime;
private long interval;
public void StartThread(long intervalInMillis)
{
interval = intervalInMillis * TimeSpan.TicksPerMillisecond;
nextExecutionTime = DateTime.Now.Ticks;
thread = new Thread(Run);
thread.Start();
}
private void Run()
{
while (true)
{
if (DateTime.Now.Ticks >= nextExecutionTime)
{
nextExecutionTime += interval;
// do stuff
}
}
}
}
如果您对计时器不满意?
那么您可以尝试让您的线程休眠5分钟,而不是使用Timer
看看这个,希望对你有帮助
using System;
using System.Threading;
public class Worker
{
// This method will be called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Task.Factory.Start(() =>
{
// do you task async
})
Thread.Sleep(300000);
}
}
public void DoWork2()
{
var watch = new Stopwatch();
while (!_shouldStop)
{
watch.Start();
Task.Factory.Start(() =>
{
// do you task async
})
while(watch.Elapsed.ElapsedMilliseconds < 300000);
watch.Stop();
watch.Reset();
}
}
public void RequestStop()
{
_shouldStop = true;
}
private volatile bool _shouldStop;
}
public class WorkerThreadExample
{
static void Main()
{
// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
// Start the worker thread.
workerThread.Start();
// Loop until worker thread activates.
while (!workerThread.IsAlive);
while (true)
{
//do something to make it break
}
// Request that the worker thread stop itself:
workerObject.RequestStop();
workerThread.Join();
}
}
或者您可以尝试以下操作:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.