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

I am working on a program that will have to delete a folder (and then recreate it) at a specific hour of the day, and this hour will be provided by the user.

The hour will most likely be at night, because when no one accesses the folder (it is outside of working hours). Is there any way to trigger this event at this specific hour?

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

EDIT . Perhaps I was not specific enough. I want to call a method to do something, without having to first compile it into a separate executable. This method is part of a larger class that is implemented as a Windows service. Thus, this service is constantly running, but at a certain time of the day it should call this function to delete the folder.

Thanks.

+4
source share
6 answers

Think out of the box.

No need to code this type of work - use Scheduled Tasks , they have been on Windows for a long time. You can start with this program.

Update : (after updating to the question)

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

+7
source

Use Windows Scheduler. There you can specify which file will be executed when.

+3
source

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

a. Calculate the time remaining until the first execution time.

 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. Set up a timer event.

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

C. Setting up the method does what you want to do.

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

When

  • the program launches
  • the timer has been changed
  • event completed

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

+2
source

Possible launch or guide: NCrontab

+1
source

The programming interface for the scheduled task is based on COM, so it should be relatively easy to use with .NET (although I’ve never tried it myself).

+1
source

Source: https://habr.com/ru/post/1304557/


All Articles