简体   繁体   中英

C# How can I trigger an event at a specific time of day?

I'm working on a program that will need to delete a folder (and then re-instantiate it) at a certain hour of the day, and this hour will be given by the user.

The hour will most likely be during the night, because that's when nobody is accessing the folder (it's outside working hours). Is there a way to trigger that event at that certain hour?

I know about timers, but is there an easier way to do this without a timer that ticks and checks to see what time it is?

EDIT : Maybe I wasn't specific enough. I want to trigger a method to do something, without having to first compile it in a separate executable. This method is part of a bigger class that is implemented as a Windows Service. So this service continuously runs, but at a certain time of day, it should trigger this function to delete the folder.

Thanks.

Think out of the box.

No need for coding on this kind of job - use Scheduled Tasks , they have been in windows for a long time. You can kick off your program from this.

Update : (following update to question)

If you need to trigger a method from an already running service, use a timer and test DateTime.Now against your target time.

If you want to do this in your code you need to use the Timer class and trigger the Elapsed event.

A. Calculate the time left until your first runtime.

 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. Setup the timer event.

 Timer execute = new Timer(); execute.Interval = timeLeftUntilFirstRun.TotalMilliseconds; execute.Elapsed += ElapsedEventHandler(doStuff); // Event to do your tasks. execute.Start();

C. Setup the method do execute what you want to do.

 public void doStuff(object sender, ElapsedEventArgs e) { // Do your stuff and recalculate the timer interval and reset the Timer. }

When

  • the program starts
  • the timer was changed
  • the event has finished

calculate the remaining time (in milliseconds) and set the Timer interval.

Use Windows Scheduler. There you can specificy which file is executed when.

一个可能的开始或指南: NCrontab

计划任务编程接口是基于 COM 的,因此从 .NET 使用它应该相对容易(尽管我自己从未尝试过)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM