在特定时间执行功能

时间:2012-10-24 08:18:09

标签: c# winforms timer

我在我的应用程序中运行了一个计时器,我希望根据当地时间停止并启动。 所以我需要这样的东西:

if ( time = 08:00) {StartTimer();}
If ( time = 18:00) {StopTimer();} //This can be done from the timer event itself

有没有办法没有使用其他计时器? 我可以在计时器事件本身内停止计时器,但我将如何重新启动计时器?

4 个答案:

答案 0 :(得分:2)

您可以将计时器的间隔时间设置为14小时,而不是将其停止或使其间隔较短并在内部检查其他条件(当天的时间)。

答案 1 :(得分:1)

你可以试试这个: -

1)创建一个可以满足您需求的控制台应用程序。

2)使用Windows“计划任务”功能让控制台应用程序在您需要运行时执行

您还可以查看此示例: -

   using System;
   using System.Threading;

    public class TimerExample {

// The method that is executed when the timer expires. Displays
// a message to the console.
private static void TimerHandler(object state) {

    Console.WriteLine("{0} : {1}",
        DateTime.Now.ToString("HH:mm:ss.ffff"), state);
}

public static void Main() {

    // Create a new TimerCallback delegate instance that 
    // references the static TimerHandler method. TimerHandler 
    // will be called when the timer expires.
    TimerCallback handler = new TimerCallback(TimerHandler);

    // Create the state object that is passed to the TimerHandler
    // method when it is triggered. In this case a message to display.
    string state = "Timer expired.";

    Console.WriteLine("{0} : Creating Timer.",
        DateTime.Now.ToString("HH:mm:ss.ffff"));

    // Create a Timer that fires first after 2 seconds and then every
    // second.
    using (Timer timer = new Timer(handler, state, 2000, 1000)) {

        int period;

        // Read the new timer interval from the console until the
        // user enters 0 (zero). Invalid values use a default value
        // of 0, which will stop the example.
        do {

            try {
                period = Int32.Parse(Console.ReadLine());
            } catch {
                period = 0;
            }

            // Change the timer to fire using the new interval starting
            // immediately.
            if (period > 0) timer.Change(0, period);

        } while (period > 0);
    }

    // Wait to continue.
    Console.WriteLine("Main method complete. Press Enter.");
    Console.ReadLine();
}
}

答案 2 :(得分:1)

你可以创建一个每秒钟滴答的线程。

在那里,您可以检查是否要启动或停止计时器。

阅读以下内容:Threads

在你的主题中添加如下内容:

if (CurrentTime == "08:00")
   StartTimer();
else if  if (CurrentTime == "18:00")
   StopTimer();
Thread.Sleep(1000); // Makes the Thread Sleep 1 Second

答案 3 :(得分:1)

由于你总是需要至少一个计时器运行(以检测早上8点的时间),那么你可以只使用一整天运行的计时器。

每当计时器滴答时,检查时间。如果它不在0800和1800之间,则不做任何事情就返回,等待下一个滴答。

您可以尝试将定时器间隔增加到一个值,例如17:55然后再次降低它,但不会有任何可衡量的性能差异所以恕我直言这是没有任何好处的工作。