How to use a timer in a console application with C#

3 Answers

0 votes
// General-purpose timers in console apps

using System;
using System.Timers;

class Program
{
    static Timer timer;

    static void Main()
    {
        timer = new Timer(1000); // 1 second
        timer.Elapsed += TimerElapsed;
        timer.AutoReset = true;
        timer.Enabled = true;

        Console.WriteLine("Timer started. Press Enter to exit.");
        Console.ReadLine();
    }

    private static void TimerElapsed(object sender, ElapsedEventArgs e) {
        Console.WriteLine("Tick: " + DateTime.Now);
    }
}


/*
run:

Timer started. Press Enter to exit.
Tick: 04/13/2026 09:17:14
Tick: 04/13/2026 09:17:15
Tick: 04/13/2026 09:17:16
Tick: 04/13/2026 09:17:17
Tick: 04/13/2026 09:17:18
Tick: 04/13/2026 09:17:19

*/

 



answered Apr 13 by avibootz
edited Apr 13 by avibootz
0 votes
// High-performance background tasks

using System;
using System.Threading;

class Program
{
    static Timer timer;

    static void Main()
    {
        timer = new Timer(Tick, null, 0, 1000); // start immediately, tick every 1 sec

        Console.WriteLine("Timer started. Press Enter to exit.");
        Console.ReadLine();
    }

    static void Tick(object state)
    {
        Console.WriteLine("Tick: " + DateTime.Now);
    }
}



/*
run:

Timer started. Press Enter to exit.
Tick: 04/13/2026 09:24:30
Tick: 04/13/2026 09:24:31
Tick: 04/13/2026 09:24:32
Tick: 04/13/2026 09:24:33
Tick: 04/13/2026 09:24:34
Tick: 04/13/2026 09:24:35

*/

 



answered Apr 13 by avibootz
0 votes
// No threads to manage

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Timer started. Press Enter to exit.");

        _ = RunTimer(); // fire and forget

        Console.ReadLine();
    }

    static async Task RunTimer() {
        while (true) {
            Console.WriteLine("Tick: " + DateTime.Now);
            await Task.Delay(1000);
        }
    }
}



/*
run:

Timer started. Press Enter to exit.
Tick: 04/13/2026 09:29:56
Tick: 04/13/2026 09:29:57
Tick: 04/13/2026 09:29:58
Tick: 04/13/2026 09:29:59
Tick: 04/13/2026 09:30:00
Tick: 04/13/2026 09:30:01
Tick: 04/13/2026 09:30:02

*/

 



answered Apr 13 by avibootz
...