簡體   English   中英

在特定時間執行功能

[英]Executing a Function at a Specific time

我在我的應用程序中運行了一個計時器,我想根據當地時間停止並啟動。 所以我需要這樣的東西:

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

有沒有辦法在使用其他計時器的情況下執行此操作? 我可以在計時器事件本身內停止計時器,但我將如何重新啟動計時器?

您可以將計時器的間隔設置為14小時,而不是將其停止或使其間隔較短並在內部檢查其他條件(一天中的時間)。

你可以試試這個: -

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

您可以創建一個每秒鍾滴答的線程。

在那里,您可以檢查是否要啟動或停止計時器。

閱讀下面的內容: 主題

在你的線程中添加如下內容:

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

因為你總是需要至少一個計時器運行(以檢測它在早上8點的時間),那么你可以只使用一整天運行的計時器。

只要計時器滴答,檢查時間。 如果它不在0800和1800之間,則只返回而不做任何事情並等待下一個滴答。

您可以嘗試將計時器間隔增加到一個值,例如17:55,然后再次減少它,但不會有任何可測量的性能差異,所以恕我直言這是沒有任何好處的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM