C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Every several seconds or minutes, it executes a method. This is useful for monitoring the health of an important program, as with diagnostics. The System.Timers namespace proves useful.
Example. This example is a static class, meaning it cannot have instance members or fields. It includes the System.Timers namespace and shows the Elapsed event function. It appends the current DateTime to a List every three seconds.
Class that uses Timer: C# using System; using System.Collections.Generic; using System.Timers; public static class TimerExample // In App_Code folder { static Timer _timer; // From System.Timers static List<DateTime> _l; // Stores timer results public static List<DateTime> DateList // Gets the results { 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 // // Type "_timer.Elapsed += " and press tab twice. // _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed); _timer.Enabled = true; // Enable it } static void _timer_Elapsed(object sender, ElapsedEventArgs e) { _l.Add(DateTime.Now); // Add date on each timer event } } Note This class has no output. It must be called elsewhere in your program.
Research. MSDN states that System.Timers "allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing."
Using Timer for periodic checks is a common requirement. Microsoft recommends it, noting that "you could create a service that uses a Timer to periodically check the server and ensure that the system is up and running."
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 from the Timer class in the .NET Framework. 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: MSDN: "Whether the Timer should raise the Elapsed event." You must 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 that is invoked each time the Interval of the Timer has passed. You must specify this function in code.
ASPX files. Continuing on, 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 an ASP.NET Literal or Label.
ASPX file that uses Timer: C# 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 } } }
This code sample starts the Timer from the DateList property accessor, and then writes all the contents of the List to the page output. With this Default.aspx page, you can use the Reload button in your web browser.
And: You will see the timer is adding to the List every three seconds. The output shows repeated time strings.
Note: This tutorial does not show an AJAX timer. For live page updates, you will need a different client-side mechanism.
Error. Often developers can hit an "Object reference not set to an instance of an object" error when using HttpContext.Current in the Timer. This is because the Timer is invoked on a separate thread.
Tip: You can work around the problem by storing important variables in static, global fields or properties.
Websites. 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.
Tip: This way, the Timer enables the website to almost always use the most recent valid file.
For mission-critical sites, you should have logic that tries to detect all errors and then handle them. This can mean visitors to your site don't encounter the errors and you detect them on the Timer.
Your ASP.NET application should have an App_Code folder. And you can add a C# file that stores a static timer object. For reference, we present material on global variables in ASP.NET, which apply to this subject.
Summary. We looked at the Timer class from the System.Timers namespace in the C# language targeting the .NET Framework. This interval-based validation approach is recommended by Microsoft for mission-critical applications.