【问题标题】:Run a certain code every x minute [closed]每x分钟运行一次特定代码[关闭]
【发布时间】:2014-12-27 04:48:51
【问题描述】:

我正在尝试制作一个程序,它每 x 分钟执行一次。我一直在试验秒表功能,但时间到了,它似乎并没有运行我想要的代码。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;

namespace Testing
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch testing = new Stopwatch();
            testing.Start();

            Thread.Sleep(6001);
            TimeSpan ts = testing.Elapsed;
            int timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
            Console.Write(timer);

            while (testing.Elapsed < TimeSpan.FromMinutes(8))
            {

                timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
                if (timer % 60 == 0)
                {
                    //run x code every 1 minutes
                    Console.WriteLine("1 min" + timer);
                }


                timer = Convert.ToInt32(String.Format("{0}", ts.Seconds));
                if (timer % 120 == 0)
                {
                    //run x code every 2 minutes
                    Console.WriteLine("2 min" + timer);
                }
            }    

            testing.Stop();
        }
    }
}

【问题讨论】:

    标签: c# timer stopwatch


    【解决方案1】:

    Stopwatch 是一个高性能计时器(通常具有 100ns 分辨率)——它完全不适合您尝试做的事情。 Stopwatch 用于通过拍摄系统计数器的快照然后计算差异来测量时间。

    由于调度程序的大部分工作是等到需要完成的工作,因此实现具有紧密循环的调度程序效率极低 - 系统正在使用 CPU 资源来决定大部分时间不做任何事情。

    要正确实施调度程序(如果您正在尝试这样做),请考虑使用带有超时选项的 ManualResetEvent

    使用事件会使您当前的线程进入睡眠状态(因此它在什么都不做的情况下不使用系统资源),当超时到期时,将触发事件并且代码可以调用您尝试安排的函数。

    如果您只想要一个简单的计时器来告诉您时间间隔何时过去,请改用System.Timers.Timer:这样可以更简单地安排回调(当计时器到期时调用Elapsed 事件)并且您在等待期间不必运行循环。

    编辑:

    如果你只是想周期性地调用一个回调函数,一个简单的定时器比一个事件更容易连接。这是一个使用 System.Timer 的代码示例(不是我的代码,我从 MSDN 复制并粘贴了这个,上面链接):

    private static Timer m_oTimer;
    
    public static void Main ()
    {
        m_oTimer = new System.Timers.Timer ( 2 * 1000 * 60 ); // 2 minutes
        m_oTimer.Elapsed += OnTimedEvent; // Timer callback
        m_oTimer.Enabled = true; // Start timer
    
        // Wait here (you can do other processing here, too)
        Console.WriteLine ( "Press the Enter key to exit the program... " );
        Console.ReadLine ();
        Console.WriteLine ( "Terminating the application..." );
    }
    
    private static void OnTimedEvent ( Object source, ElapsedEventArgs e )
    {
        // This is called on a separate thread; do periodic processing here
        Console.WriteLine ( "The Elapsed event was raised at {0}", e.SignalTime );
    }
    

    【讨论】:

    • 您好,xxbbcc,感谢您的回复。根据您的建议,我一直在尝试 ManualResetEvent,因为它似乎适合我想要做的更多事情,但是我只能设法使代码使用计时器运行一次,我正在寻找的是每 x 分钟,代码将运行一次。例如,我将程序运行时间设置为 30 分钟。在 30 分钟的运行时间内,我希望程序每 2 分钟重复一次 Console.WriteLine("2 minutes is up") 直到 30 分钟结束。请帮帮我:)
    • @Konny 我使用System.Timers.Timer 用一些代码更新了我的答案。
    【解决方案2】:

    按照 xxbbcc 的建议,这是一个使用 ManualResetEvent.WaitOne() 和 TimeOut 的实现:

        static void Main(string[] args)
        {
            int TimeOut = (int)TimeSpan.FromMinutes(2).TotalMilliseconds;
            System.Threading.ManualResetEvent mreDuration = new System.Threading.ManualResetEvent(false);
            Task.Run(() => {
                System.Threading.Thread.Sleep((int)TimeSpan.FromMinutes(30).TotalMilliseconds);
                mreDuration.Set();
            });
            while(!mreDuration.WaitOne(TimeOut))
            {
                Console.WriteLine("Two Minutes...");
            }
            Console.WriteLine("Thirty Mintues!");
            Console.ReadLine();
        }
    

    【讨论】:

      【解决方案3】:

      您应该使用Timer。如果您希望计时器在“y”分钟后停止运行,那么您只需将开始时间存储在一个变量中并编写Timer.Stop() 函数,以便它在“y”分钟后执行(提示:将其写入timer_tick 事件)。计时器的时间段应该是所有 xyHCF。请记住以毫秒为单位设置时间段。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-17
        • 2014-11-02
        • 2016-03-28
        • 1970-01-01
        相关资源
        最近更新 更多