Home
Search
C# Timer ExamplesMonitor processes with the Timer class from the System.Timers namespace.
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. 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.
Part 1 We set up the Timer. The Elapsed event handler is called every 3 seconds. We store the Timer as a static field.
Part 2 The code here adds the current DateTime to a List every 3 seconds (when the Timer is invoked).
DateTime
List
Part 3 We call PrintTimes. We wait 2 seconds between calls 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() { // Part 1: setup 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) { // Part 2: 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(); // Part 3: call PrintTimes every 3 seconds. while (true) { // Print results. TimerExample.PrintTimes(); // Wait 2 seconds. Console.WriteLine("WAITING"); System.Threading.Thread.Sleep(2000); } } }
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); } }
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
Using statement. Timers allocate system resources, so if you are creating a lot of them, make sure to Dispose them. It is usually easier to just have a single static timer instance.
Using
Here We create a Timer in a using-statement. It runs every 3 seconds, and its resources are cleaned up correctly at the end of the block.
C# program that uses Timer in using-statement
using System; using System.Timers; class Program { static void Main() { // Use Timer in a using-statement. // ... This ensures it is disposed correctly. using (Timer timer = new Timer()) { timer.Interval = 1000; timer.Elapsed += Timer_Elapsed; timer.Start(); System.Threading.Thread.Sleep(10000); } } private static void Timer_Elapsed(object sender, ElapsedEventArgs e) { Console.WriteLine("ONE SECOND PASSED"); } }
ONE SECOND PASSED ONE SECOND PASSED ONE SECOND PASSED ONE SECOND PASSED ONE SECOND PASSED ONE SECOND PASSED ONE SECOND PASSED ONE SECOND PASSED ONE SECOND PASSED
Timer, ASP.NET Core. It is possible to use a Timer in an ASP.NET Core. First, create an ASP.NET Core Web application, and then modify the Configure method in the Startup file.
Endpoints We set up the endpoints with UseEndpoints, and call WriteAsync with the string returned by DateList.
TimerExample We create a Timer when DateList is called, and also allocate the List. We call Start on the timer.
Result The Timer's Elapsed event is called every 3 seconds, and DateTime.Now is added to the list.
DateTime.Now
Tip Refresh the page in your browser, and it will have added a new date string every 3 seconds on the server.
C# program that sets up Endpoints
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; namespace WebApplication1 { public class Startup { public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { // Write the times. await context.Response.WriteAsync(TimerExample.DateList); }); }); } } }
using System; using System.Collections.Generic; using System.Text; using System.Timers; public class TimerExample { static Timer _timer; static List<DateTime> _dates; public static string DateList { get { // Lazily initialize the list and timer. if (_dates == null) { _dates = new List<DateTime>() { DateTime.Now }; // Run timer every 3 seconds. _timer = new Timer(3000); _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed); _timer.Enabled = true; } // Return string containing all our times. var builder = new StringBuilder(); foreach (var date in _dates) { builder.Append(date).Append('\n'); } return builder.ToString(); } } static void _timer_Elapsed(object sender, ElapsedEventArgs e) { // Add date on each timer event. _dates.Add(DateTime.Now); } }
3/22/2020 7:33:36 AM 3/22/2020 7:33:39 AM 3/22/2020 7:33:42 AM
Notes, ASP.NET Core. It is possible to use a timer in older web technologies like Web Forms as well. We can store a Timer in a class, and run it on the server.
A summary. The Timer class from the System.Timers namespace can be used to run code on an interval. An interval-based validation approach is recommended for important applications.
Home
© 2007-2021 sam allen. see site info on the changelog