HomeSearch

C# Timer Examples

This C# page uses the Timer class from the System.Timers namespace. A Timer monitors processes.

Timer.

This class regularly invokes code. Every several seconds or minutes, it executes a method. This is useful for monitoring the health of a program, as with diagnostics.

A namespace.

The System.Timers namespace proves useful. With a Timer, we can ensure nothing unexpected has happened. We can also run a periodic update (to do anything).

First example.

Here, TimerExample is a static class, meaning it cannot have instance members or fields. We include the System.Timers namespace and see the Elapsed event function.Static

Info: The code here adds the current DateTime to a List every 3 seconds (when the Timer is invoked).

DateTimeList

Sleep: We wait 2 seconds between calling PrintTimes() for the demonstration—this is separate from the core timer functionality.

Sleep
C# program that uses Timer using System; using System.Collections.Generic; using System.Timers; static class TimerExample { static Timer _timer; static List<DateTime> _results = new List<DateTime>(); public static void Start() { // Set up the timer for 3 seconds. var timer = new Timer(3000); // To add the elapsed event handler: // ... Type "_timer.Elapsed += " and press tab twice. timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed); timer.Enabled = true; _timer = timer; } static void _timer_Elapsed(object sender, ElapsedEventArgs e) { // Add DateTime for each timer event. _results.Add(DateTime.Now); } public static void PrintTimes() { // Print all the recorded times from the timer. if (_results.Count > 0) { Console.WriteLine("TIMES:"); foreach (var time in _results) { Console.Write(time.ToShortTimeString() + " "); } Console.WriteLine(); } } } class Program { static void Main() { TimerExample.Start(); while (true) { // Print results. TimerExample.PrintTimes(); // Wait 2 seconds. Console.WriteLine("WAITING"); System.Threading.Thread.Sleep(2000); } } } Output WAITING WAITING TIMES: 6:43 AM WAITING TIMES: 6:43 AM 6:43 AM WAITING TIMES: 6:43 AM 6:43 AM WAITING TIMES: 6:43 AM 6:43 AM 6:43 AM WAITING TIMES: 6:43 AM 6:43 AM 6:43 AM 6:43 AM WAITING TIMES: 6:43 AM 6:43 AM 6:43 AM 6:43 AM WAITING TIMES: 6:43 AM 6:43 AM 6:43 AM 6:43 AM 6:43 AM WAITING

SignalTime.

Here is another Timer example. Notice how the TimerElapsed event is added directly—no ElapsedEventHandler call is needed.

Start: We start the timer, and then run an infinite loop (this is not a good programming approach).

SignalTime: The ElapsedEventArgs has a SignalTime property, which is a DateTime struct. This is the time the Timer was fired.

DateTime
C# program that uses SignalTime using System; using System.Timers; class Program { static void Main() { Timer timer = new Timer(200); timer.Elapsed += Timer_Elapsed; timer.Start(); while (true) { // Infinite loop. } } private static void Timer_Elapsed(object sender, ElapsedEventArgs e) { // Use SignalTime. DateTime time = e.SignalTime; Console.WriteLine("TIME: " + time); } } Output TIME: 4/3/2019 2:10:55 PM TIME: 4/3/2019 2:10:55 PM TIME: 4/3/2019 2:10:56 PM TIME: 4/3/2019 2:10:56 PM TIME: 4/3/2019 2:10:56 PM TIME: 4/3/2019 2:10:56 PM

Research.

Microsoft states that System.Timers "allows you to specify a recurring interval at which the Elapsed event is raised in your application."

And: We can "then handle this event to provide regular processing." Using Timer for periodic checks is a common requirement.

Quote: You could create a service that uses a Timer to periodically check the server and ensure that the system is up and running.

Timer Class: Microsoft Docs

Dispose.

Timers allocate system resources, so if you are creating a lot of them, make sure to Dispose them. This gets complicated fast. I suggest just using a single static timer.

Properties.

These are notes on properties, methods and events for Timer. As shown above, you need to add the System.Timers namespace at the top of your file for easy access to Timer.

Timer.AutoReset: Indicates "whether the Timer should raise the Elapsed event each time the specified interval elapses."

Timer.Enabled: Microsoft: "Whether the Timer should raise the Elapsed event." Set this to true if you want your timer to do anything.

Timer.Interval: The number of milliseconds between Elapsed events being raised. Here "the default is 100 milliseconds."

Timer.Start: This does the same thing as setting Enabled to true. It is unclear why we need this duplicate method.

Timer.Stop: This does the same thing as setting Enabled to false. See the Timer.Start method previously shown.

Timer.Elapsed Event: An event (ElapsedEventHandler) that is invoked each time the Interval of the Timer has passed.

ASPX files.

This ASP.NET page uses the Timer code. Your .aspx file should have a code-behind file. If your project uses web forms, you could assign the List values to a Literal or Label.

Note: We start the Timer from the DateList property accessor. We then write all the contents of the List to the page output.

Reload: With this Default.aspx page, you can use the Reload button in your web browser. The timer adds to the List every three seconds.

C# program that implements DateList property using System; using System.Collections.Generic; using System.Timers; public static class TimerExample { static Timer _timer; static List<DateTime> _l; public static List<DateTime> DateList { get { if (_l == null) // Lazily initialize the timer. { Start(); // Start the timer. } return _l; // Return the list of dates. } } static void Start() { _l = new List<DateTime>(); // Allocate the list. _timer = new Timer(3000); // Set up the timer for 3 seconds. _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed); _timer.Enabled = true; } static void _timer_Elapsed(object sender, ElapsedEventArgs e) { _l.Add(DateTime.Now); // Add date on each timer event. } } C# program that uses Timer, Page_Load using System; using System.Web; using System.Web.UI; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { HttpResponse r = Response; // Get reference to Response foreach (DateTime d in TimerExample.DateList) // Get the timer results { r.Write(d); // Write the DateTime r.Write("<br/>"); // Write a line break tag } } }

Error, ASP.NET.

We can hit an "Object reference not set to an instance of an object" error when using HttpContext.Current in the Timer.

And: This is because the Timer is invoked on a separate thread. To fix, try using static (global) fields or properties.

Property

Notes, ASP.NET.

You can use a Timer instance to monitor your ASP.NET site. You can check the file system for changes to the App_Data folder.

And: When new files are detected, they are parsed and checked for errors. This does affect need to affect site performance.

Tip: This way, the Timer enables the website to almost always use the most recent valid file.

Notes, continued.

With a Timer, you can have logic that tries to detect all errors and then handle them. This can mean visitors don't encounter the errors and you detect them on the Timer.

Tip: Your ASP.NET application should have an App_Code folder. And you can add a C# file that stores a static timer object.

A summary.

We looked at the Timer class from the System.Timers namespace. This interval-based validation approach is recommended by Microsoft for important applications.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.