[英]C# How can I trigger an event at a specific time of day?
我正在開發一個程序,該程序需要在一天中的某個時間刪除一個文件夾(然后重新實例化它),這個時間將由用戶指定。
這個時間很可能是在晚上,因為那時沒有人訪問該文件夾(工作時間之外)。 有沒有辦法在特定時間觸發該事件?
我知道計時器,但是有沒有更簡單的方法來做到這一點,而沒有計時器可以滴答並檢查時間?
編輯:也許我不夠具體。 我想觸發一個方法來做某事,而不必先在單獨的可執行文件中編譯它。 此方法是作為 Windows 服務實現的更大類的一部分。 所以這個服務一直在運行,但是在一天中的某個時間,它應該觸發這個函數來刪除文件夾。
謝謝。
打破常規思考問題。
不需要在這種工作上編碼 - 使用計划任務,它們在 Windows 中已經存在很長時間了。 你可以從這里開始你的程序。
更新:(在問題更新之后)
如果您需要從已運行的服務觸發方法,請使用計時器並針對您的目標時間測試DateTime.Now
。
如果要在代碼中執行此操作,則需要使用 Timer 類並觸發 Elapsed 事件。
A. 計算距您的第一個運行時間還剩多少時間。
TimeSpan day = new TimeSpan(24, 00, 00); // 24 hours in a day. TimeSpan now = TimeSpan.Parse(DateTime.Now.ToString("HH:mm")); // The current time in 24 hour format TimeSpan activationTime = new TimeSpan(4,0,0); // 4 AM TimeSpan timeLeftUntilFirstRun = ((day - now) + activationTime); if(timeLeftUntilFirstRun.TotalHours > 24) timeLeftUntilFirstRun -= new TimeSpan(24,0,0); // Deducts a day from the schedule so it will run today.
B. 設置定時器事件。
Timer execute = new Timer(); execute.Interval = timeLeftUntilFirstRun.TotalMilliseconds; execute.Elapsed += ElapsedEventHandler(doStuff); // Event to do your tasks. execute.Start();
C. 設置方法執行你想做的事情。
public void doStuff(object sender, ElapsedEventArgs e) { // Do your stuff and recalculate the timer interval and reset the Timer. }
什么時候
計算剩余時間(以毫秒為單位)並設置定時器間隔。
使用 Windows 調度程序。 在那里您可以指定何時執行哪個文件。
一個可能的開始或指南: NCrontab
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.