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

后端 未结 6 470
走了就别回头了
走了就别回头了 2021-01-03 04:59

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 h

相关标签:
6条回答
  • 2021-01-03 05:17

    The programmatic interface for Scheduled Task is COM-based, so it should be relatively easy to use it from .NET (though I've never tried myself).

    0 讨论(0)
  • 2021-01-03 05:21

    A possible start or guideline : NCrontab

    0 讨论(0)
  • 2021-01-03 05:29

    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.
     }
    
    0 讨论(0)
  • 2021-01-03 05:31

    When

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

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

    0 讨论(0)
  • 2021-01-03 05:35

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

    0 讨论(0)
  • 2021-01-03 05:36

    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.

    0 讨论(0)
提交回复
热议问题