
Execute Tasks Periodically
by Alberto Falossi
November 2002 Issue
Technology Toolbox: VB.NET, C#
Level: Intermediate
Applications often need to execute some tasks periodically. For example, a server application might need to back up its data every hour. You must use a timer to enable this feature. A timer lets you delay, and repeat regularly, execution of a routine. The .NET Framework provides three timers: System.Timers.Timer, System.Threading.Timer, and System.Windows.Forms.Timer.
System.Timers.Timer and System.Threading.Timer are the server-based timers, and System.Windows.Forms.Timer is the Windows timer. Each timer exposes substantially the same features as the others, but has a different internal implementation and is optimized for different scenarios. In broad terms, you use Windows timers on WinForms applications, and server-based timers on other types of applications.
System.Timers.Timer is the most complete and accurate .NET timer. This C# code shows you how to use this timer to delay the printing of the sentence "Hello World" for five seconds:
// using System.Timers;
void TestTimer()
{
// create the timer set the event handler
Timer timer = new Timer();
// set the event handler
timer.Elapsed += new
ElapsedEventHandler(OnElapsed);
// set the timer properties
timer.Interval = 5000;
timer.AutoReset = true;
// start the timer
timer.Start();
}
void OnElapsed(Object sender, ElapsedEventArgs e)
{
// on timeout this code is executed
Console.WriteLine("Hello World!");
}
The OnElapsed event handler contains the code to execute when the timeout expires. The Interval property contains the timeout value in milliseconds. The AutoReset property specifies whether to start the timer again after the timeout has elapsed. If you set the AutoReset to false, the elapsed event fires only once; if you set AutoReset to true, the elapsed event fires every five seconds. Start and stop the timer by calling the Start and Stop methods or assigning the Enabled property.
Server-based timers use the thread pool internally, and the event handler runs in a thread taken from the pool. For this reason, conflicts might occur while the event handler is accessing shared variables and modifying controls and forms. See the System.Timers.Timer.SynchronizingObject documentation in the .NET Framework SDK to work around the problem.
Back to top
|