O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.11. Configuring a Timer

Problem

You have one of the following timer configuration needs:

  • You want to use a timer to call a timer callback method at a fixed time after the timer object has been created. Once this callback method has been called the first time, you want to call this same callback method at a specified interval (this interval might be different from the time interval between the creation of the timer and the first time the timer callback method is called).

  • You want to use a timer to call a timer callback method immediately upon creation of the System.Threading.Timer object, after which the callback method is called at a specified interval.

  • You want to use a timer to call a timer callback method one time only.

  • You have been using a System.Threading.Timer object and need to change the intervals at which its timer callback method is called.

Solution

To fire a System.Threading.Timer after an initial delay, and then at a specified period after that, use the System.Threading.Timer constructor to set up different times for the initial and following callbacks:

using System; using System.Threading; public class TestTimers { public static int count = 0; public static Timer timerRef = null; public static void Main( ) { TimerCallback callback = new TimerCallback(TimerMethod); // Create a timer that waits one half second, then invokes // the callback every second thereafter. Timer timer = new Timer(callback, null,500, 1000); // store a reference to this timer so the callback can ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required