R. Hodges
R. Hodges

Reputation: 73

How Do I Pause a System.Timer in Visual Basic?

I am using a system.timer in a Windows Service to run a process that usually exceeds the timer's interval. I am trying to keep the timer from firing the same code more than once, a known issue with system.timers.

What I want: The timer runs my code, but the timer "pauses" to wait until the code is completed before resuming ticks.

I have two problems:

  1. The way system.timers work is that the timer will create a race condition on you by launching new redundant threads of the same code and pile them up on you if the has not completed by the time the timer's interval has elapsed.

  2. I would start/stop the timer to keep this from happening, but with a System.Timers.Timer, once you stop the timer for the processing to complete, it never comes back - I have never been able to restart a timer once it has been stopped, it has been destroyed and likely collected. Enabling/disabling is the same exact thing as start/stop with same results.

How on earth do you keep a system.timer from launching new redundant threads of the same code if the process has not completed by the time the timer's interval has lapsed? Obviously, starting/stopping (enabling/disabling) the timer is NOT a solution, as it doesn't work.

Help!

Upvotes: 2

Views: 1587

Answers (2)

raddevus
raddevus

Reputation: 9077

The Start and Stop methods on the Timer do actually work in a Windows service. I have multiple production services which use code that do that, except my code is written in C#.

However, make sure you are using the System.Timers.Timer and not the Windows.Forms.Timer

Here's a quick example of C# / pseudocode of what my services look like.

// this is the OnStart() event which fires when windows svc is started
private void OnStart()
{
    // start your timer here.
    MainTimer.Start();
}

private void ElapsedEventHandler()
{
      try
      { 
          // Stop the timer, first thing so the problem of another timer
          // entering this code does not occur
          MainTimer.Stop();

          //Do work here...   
      }
      catch (Exception ex)
      { 
          // if you need to handle any exceptions - write to log etc.
      }
      finally
      {
         MainTimer.Start();
         // finally clause always runs and will insure
         // your timer is always restarted.
      }
}

Upvotes: 1

Tertius Geldenhuys
Tertius Geldenhuys

Reputation: 358

Start your timer when it needs to start, kick off another thread to do the work after which the timer can be stopped. The timer won't care if the thread completed or ran away with the prize money. Use Task Parallel Library (TPL) for the most effective usage.

Upvotes: 2

Related Questions