C# 相当于 Java 的 timer.scheduleAtFixedRate

标签 c# timer

我需要一种每 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
            }
        }
    }
}

最佳答案

如果您对 Timer 不满意?

然后你可以尝试让你的线程休眠 5 分钟,而不是使用定时器

看看这个,希望对你有帮助

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();
    }
}

或者你可以试试这个:

关于C# 相当于 Java 的 timer.scheduleAtFixedRate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15876219/

相关文章:

c# - 选择随机节点并添加到标签

c# - 将 JSON 转换为 C# 类型

java - 如何计算到设定时间的剩余时间

java - 定时器:周期小于一毫秒

vba - Excel 2016 在 API 计时器启动时崩溃 Workbook.close

c# windows-services - 如何处理日志记录异常?

c# - 如何获取和更改未命名控件的属性?

javascript - 如何在控制台中重复调用javascript函数

linux - 是否可以在信号处理程序中设置计时器?

c# - 错误 : 26 - Error Locating Server/Instance Specified.(无法从我的主机服务器连接到我的本地数据库)