Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#相当于Java';s timer.scheduleAtFixedRate_C#_Timer - Fatal编程技术网

C#相当于Java';s timer.scheduleAtFixedRate

C#相当于Java';s timer.scheduleAtFixedRate,c#,timer,C#,Timer,我需要一种每5分钟准确运行一次的方法。我无法使用计时器,因为我注意到它将慢慢失去同步(即,它最终将在00:01、00:06、00:11、00:16等时间运行) 虽然它需要精确,但我不需要太精确。每5分钟+/-1秒就可以了,只要经过几天的跑步,它仍能准确地在5分钟标记上打勾 到目前为止,我想到的是创建一个间隔为1秒的计时器,不断检查DateTime。现在看看下一个5分钟标记是否通过。我想知道在C#库中是否有一个更优雅的解决方案或我错过的东西 编辑:我现在有以下模板,它符合我的要求 public c

我需要一种每5分钟准确运行一次的方法。我无法使用计时器,因为我注意到它将慢慢失去同步(即,它最终将在00:01、00:06、00:11、00:16等时间运行)

虽然它需要精确,但我不需要太精确。每5分钟+/-1秒就可以了,只要经过几天的跑步,它仍能准确地在5分钟标记上打勾

到目前为止,我想到的是创建一个间隔为1秒的计时器,不断检查DateTime。现在看看下一个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分钟,而不是使用计时器

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

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();
    }
}
使用系统;
使用系统线程;
公社工人
{
//线程启动时将调用此方法。
公共工作
{
而(!\u应该停止)
{
Task.Factory.Start(()=>
{
//你的任务是异步的吗
})
睡眠(30万);
}
}
公共无效工作2()
{
var watch=新秒表();
而(!\u应该停止)
{
watch.Start();
Task.Factory.Start(()=>
{
//你的任务是异步的吗
})
while(watch.eassed.elapsedmillyses<300000);
看,停;
watch.Reset();
}
}
公共void RequestStop()
{
_shouldStop=true;
}
私人的不稳定行为应该停止;
}
公共类WorkerThread示例
{
静态void Main()
{
//创建线程对象。这不会启动线程。
工人工人对象=新工人();
线程工作线程=新线程(workerObject.DoWork);
//启动辅助线程。
workerThread.Start();
//循环,直到工作线程激活。
而(!workerThread.IsAlive);
while(true)
{
//做点什么使它破裂
}
//请求工作线程停止自身:
workerObject.RequestStop();
workerThread.Join();
}
}

或者您可以尝试以下操作:

您是否确实尝试过使用System.Threading.Timer?它每隔指定的时间间隔启动一个新线程,我从未让它失去同步超过一秒钟。计时器唯一的问题是,当工作线程挂起或运行太长时间时,它将启动新线程和新线程,有时应用程序将消耗太多资源。在某些情况下,这样的行为是不合适的-然后您可以实现自己的定期运行程序。否则,请使用TimerI。我刚刚尝试过System.Threading.Timer,间隔1秒,但它在4分钟内已增加230毫秒。因此,在第一次运行和第次运行之间是否需要保证1s+(5*runId)分钟的间隔?在这种情况下,定时器真的不能保证它。它保证连续运行之间的间隔。所以我不能推荐任何比创建自己的具有这种功能的类更好的东西(这应该不难)是的,我想我必须这样做。我浏览了Java源代码,它使用了executionTime变量,并运行了一个线程,该线程根据executionTime重复检查当前时间。达到executionTime时,executionTime+=间隔。我将复制这个。它将每5分钟运行一次,无论执行任务需要多长时间。如果我的任务需要30秒运行,它将每5分30秒运行一次。当然。我想很容易计算出任务的实际执行时间((DateTime.Now-someTimeBefore).TotalSeconds),除非需要超过5分钟。如果你没有得到比计时器更好的东西,那么这可能比“创建一个间隔为1秒的计时器,不断检查日期时间。现在看看下一个5分钟标记是否通过”要好。顺便说一句,如果你想计算时间,试试秒表,它应该比DateTime更精确,这是我在endHey~~中使用的方法,我忘了C#可以执行异步函数调用!查看编辑后的答案,我们不需要做减法。此外,还有另一个版本的DoWork,它使用秒表,人们说它比DateTime更精确