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 ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.