How to Schedule a windows service using topshelf in c# at specific time in a each day

641 Views Asked by At
_timer = new Timer(1.8e+6) { AutoReset = true };
_timer.Elapsed += TimerElapsed;
1

There are 1 best solutions below

0
Moiez Hussain On

To make it run for a specific time of a day you have to make your timer set for that Time/value by finding out the difference from the current time when your service starts, find the difference between your current time and your specific time and sets the timer with that value.

public void Start() 
{
  ResetTimer();
}

public void TimerElapsed (object sender, ElapsedEventArgs e)
{
    // do whatever it is that you need to do on a timer
    ResetTimer();
}
public void ResetTimer()
{
        DateTime startTime=DateTime.Now;// = "current time";
        DateTime endTime = DateTime.Parse("Specific time to run the service");

        if (endTime < startTime)
        {
            endTime.AddDays(1);
        }           
        
        TimeSpan duration = endTime.Subtract(startTime);        
    
        _timer.Change(TimeSpan.FromSeconds(duration.Seconds), 
         TimeSpan.FromSeconds(duration.Seconds));
        _timer.Elapsed += TimerElapsed; //if not set

}