TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Timer Examples

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

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

DateTimeList

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: 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) { // 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); } } } 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.

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
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"); } } Output 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); }); }); } } } C# program that uses Timer and DateList property 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); } } Output 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.
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.

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
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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf