Calling method at the start of windows service in c#

Please look at this piece of code

 public partial class TestService : ServiceBase
 {
     private static System.Timers.Timer aTimer;

     protected override void OnStart(string[] args)
     {
        aTimer = new Timer(10000 * 6 * 5); //  5 minutes interval
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true;
     }

     private void OnTimedEvent(object source, ElapsedEventArgs e)
     {
      ......
     }
 }

When I start this service at say 4:00 pm, the first time OnTimedEvent is called is at 4:05 pm, then 4:10 pm and so on. I would like the OnTimedEvent to be called at 4:00 pm as soon as I start the service. Is there anything I am missing here?

Answers


Use a System.Threading.Timer rather than a System.Timers.Timer.

It has a constructor overload that in addition to specifying the interval allows you choose the start delay, which can be set to 0 to fire immediately.

For a Comparison of the timer classes, see Windows.Forms.Timer OR System.Threading.Timer (specifically 'Initial timer event schedulable?')


You could just call the event in the OnStart

OnTimedEvent(this, null)

System.Timers.Timer starts counting down from 5 minutes and then the event is triggered. So it won't be able to trigger and run the code till the timer reaches 0.

The code may be run before the event listener is enabled this way shown below:

public partial class TestService : ServiceBase
 {
     private static System.Timers.Timer aTimer;

     protected override void OnStart(string[] args)
     {
        aTimer = new Timer(10000 * 6 * 5); //  5 minutes interval
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        
        foo();
        aTimer.Enabled = true;
     }

     private void OnTimedEvent(object source, ElapsedEventArgs e)
     {
       foo();
     }

     private void foo(){
        .....
     }
 }

Need Your Help

SQL - Select integer in complex field (CAST and LIKE operators)

mysql sql sqlite

I have a table TabCustomer containing a number of fields.