1

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?

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
blue piranha
  • 3,706
  • 13
  • 57
  • 98

3 Answers3

0

You could just call the event in the OnStart

OnTimedEvent(this, null)
PCG
  • 1,197
  • 9
  • 23
0

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?')

Community
  • 1
  • 1
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
0

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(){
        .....
     }
 }