C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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).
DateTimeListPart 3: We call PrintTimes. We wait 2 seconds between calls for the demonstration—this is separate from the core timer functionality.
SleepC# 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
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
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
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.NowTip: 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
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.
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