159

How do you add a timer to a C# console application?

It would be great if you could supply some example coding.

2
  • 21
    Caution: the answers here have a bug, the Timer object is going to get garbage collected. The reference to the timer must be stored in a static variable to ensure it keeps ticking. Commented Dec 14, 2014 at 21:45
  • 3
    @HansPassant You seem to have missed the clear statement in my answer: "It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically. This will avoid possibly premature garbage collection of your timer object." If people want to copy a random example and use it blindly that's their problem. Commented Sep 2, 2019 at 12:18

12 Answers 12

150

That's very nice. However, in order to simulate some time passing, we need to run a command that takes some time, and that's very clear in the second example.

However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the garbage collector to do something like that.

We can see this modification in the code from the same book, CLR Via C#, third edition.

using System;
using System.Threading;

public static class Program
{
   private Timer _timer = null;
   public static void Main()
   {
      // Create a Timer object that knows to call our TimerCallback
      // method once every 2000 milliseconds.
      _timer = new Timer(TimerCallback, null, 0, 2000);
      // Wait for the user to hit <Enter>
      Console.ReadLine();
   }

   private static void TimerCallback(Object o)
   {
      // Display the date/time when this method got called.
      Console.WriteLine("In TimerCallback: " + DateTime.Now);
   }
}
Sign up to request clarification or add additional context in comments.

9 Comments

Khalid, this was extremely helpful. Thanks. The console.readline() and the GC.Collect was just what I needed.
@Ralph Willgoss, Why GC.Collect(); is required?
@Puchacz I don't see a point of calling GC.Collect(). There is nothing to collect. It would make sense, if GC.KeepAlive(t) was called after Console.ReadLine();
It terminated after first callback
@Khalid Al Hajami "However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the Garbage Collector to do some thing like that." This is absolute nonsensical rubbish. The garbage collector is utterly irrelevant. Did you copy this from a book and not understand what you were copying?
|
79

Use the System.Threading.Timer class.

System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.

There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway.

It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically. This will avoid possibly premature garbage collection of your timer object.

Here's an example of a timer in a console application:

using System; 
using System.Threading; 
public static class Program 
{ 
    public static void Main() 
    { 
       Console.WriteLine("Main thread: starting a timer"); 
       Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); 
       Console.WriteLine("Main thread: Doing other work here...");
       Thread.Sleep(10000); // Simulating other work (10 seconds)
       t.Dispose(); // Cancel the timer now
    }
    // This method's signature must match the TimerCallback delegate
    private static void ComputeBoundOp(Object state) 
    { 
       // This method is executed by a thread pool thread 
       Console.WriteLine("In ComputeBoundOp: state={0}", state); 
       Thread.Sleep(1000); // Simulates other work (1 second)
       // When this method returns, the thread goes back 
       // to the pool and waits for another task 
    }
}

From the book CLR Via C# by Jeff Richter. By the way this book describes the rationale behind the 3 types of timers in Chapter 27. Compute-Bound Asynchronous Operations, highly recommended.

6 Comments

Can you supply a little more information on the actual coding?
Does the example from msdn work for you? msdn.microsoft.com/en-us/library/system.threading.timer.aspx
Eric, I haven't tried it but would not be unusual if there was a problem with it. I notice it is also trying to do some sort of inter-thread synchronisation, this is alsways an area that can be tricky to get right. If you can avoid it in your design, it is always smart to do so.
Ash - I definitely agree about msdn examples. I wouldn't immediately discount the synchronization code though, if the timmer runs in it's own thread, then you are writing a multi-threaded app and need to be aware of issues relating to synchronization.
What happens if there are multiple methods that match the TimerCallback delegate signature?
|
30

Here is the code to create a simple one-second timer tick:

  using System;
  using System.Threading;

  class TimerExample
  {
      static public void Tick(Object stateInfo)
      {
          Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
      }

      static void Main()
      {
          TimerCallback callback = new TimerCallback(Tick);

          Console.WriteLine("Creating timer: {0}\n",
                             DateTime.Now.ToString("h:mm:ss"));

          // Create a one-second timer tick
          Timer stateTimer = new Timer(callback, null, 0, 1000);

          // Loop here forever
          for (; ; )
          {
              // Add a sleep for 100 milliseconds to reduce CPU usage
              Thread.Sleep(100);
          }
      }
  }

And here is the resulting output:

C:
cd \temp
timer.exe

Output:

Creating timer: 5:22:40

Tick: 5:22:40
Tick: 5:22:41
Tick: 5:22:42
Tick: 5:22:43
Tick: 5:22:44
Tick: 5:22:45
Tick: 5:22:46
Tick: 5:22:47

It is never a good idea to add hard spin loops into code as they consume CPU cycles for no gain. In this case, that loop was added just to stop the application from closing, allowing the actions of the thread to be observed. But for the sake of correctness and to reduce the CPU usage, a simple Sleep call was added to that loop.

7 Comments

The for (; ; ) { } causes 100% cpu usage.
Isn't it fairly obvious if you have an infinite for loop then that will result in a CPU of 100%. To fix that all you need to do is add a sleep call to the loop.
It is amazing how many people are fixated on whether the for loop should be a while loop and why the CPU goes to 100%. Talk about miss the wood for the trees! Azimuth, I would personally like to know how a while(1) would be any different to the infinite for loop? Surely the people that write the CLR compiler optimiser will make sure these two code constructs create the exact same CLR code?
One reason why while(1) will not work is it is not valid c#: test.cs(21,20): error CS0031: Constant value '1' cannot be converted to a 'bool'
Not on my machine (win8.1, i5), only about 20-30%, what kind of computer did you have back then? @SethSpearman
|
18

Let’s have a little fun:

using System;
using System.Timers;

namespace TimerExample
{
    class Program
    {
        static Timer timer = new Timer(1000);
        static int i = 10;

        static void Main(string[] args)
        {
            timer.Elapsed+=timer_Elapsed;
            timer.Start(); Console.Read();
        }

        private static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            i--;

            Console.Clear();
            Console.WriteLine("=================================================");
            Console.WriteLine("                  DEFUSE THE BOMB");
            Console.WriteLine("");
            Console.WriteLine("                Time Remaining:  " + i.ToString());
            Console.WriteLine("");
            Console.WriteLine("=================================================");

            if (i == 0)
            {
                Console.Clear();
                Console.WriteLine("");
                Console.WriteLine("==============================================");
                Console.WriteLine("         B O O O O O M M M M M ! ! ! !");
                Console.WriteLine("");
                Console.WriteLine("               G A M E  O V E R");
                Console.WriteLine("==============================================");

                timer.Close();
                timer.Dispose();
            }

            GC.Collect();
        }
    }
}

Comments

10

Or using Rx, short and sweet:

static void Main()
{
    Observable.Interval(TimeSpan.FromSeconds(10)).Subscribe(t => Console.WriteLine("I am called... {0}", t));

    for (; ; )
    {
    }
}

3 Comments

the best solution, really!
very unreadable and against best practice. It looks awesome but should not be used in production because some ppl will go wtf and poo themselves.
Reactive Extensions (Rx) has not been actively developed for 2 years. In addition the examples are without context and confusing. Little to know diagrams or flow examples.
4

You can also use your own timing mechanisms if you want a little more control, but possibly less accuracy and more code/complexity, but I would still recommend a timer. Use this though if you need to have control over the actual timing thread:

private void ThreadLoop(object callback)
{
    while(true)
    {
        ((Delegate) callback).DynamicInvoke(null);
        Thread.Sleep(5000);
    }
}

would be your timing thread(modify this to stop when reqiuired, and at whatever time interval you want).

and to use/start you can do:

Thread t = new Thread(new ParameterizedThreadStart(ThreadLoop));

t.Start((Action)CallBack);

Callback is your void parameterless method that you want called at each interval. For example:

private void CallBack()
{
    //Do Something.
}

1 Comment

If I want to run a batch job until it times out, would your suggestion here be the best one?
3

In C# 5.0+ and .NET Framework 4.5+ you can use async/await:

async void RunMethodEvery(Action method, double seconds)
{
    while (true)
    {
        await Task.Delay(TimeSpan.FromSeconds(seconds));
        method();
    }
 }

Comments

2

You can also create your own (if unhappy with the options available).

Creating your own Timer implementation is pretty basic stuff.

This is an example for an application that needed COM object access on the same thread as the rest of my codebase.

/// <summary>
/// Internal timer for window.setTimeout() and window.setInterval().
/// This is to ensure that async calls always run on the same thread.
/// </summary>
public class Timer : IDisposable {

    public void Tick()
    {
        if (Enabled && Environment.TickCount >= nextTick)
        {
            Callback.Invoke(this, null);
            nextTick = Environment.TickCount + Interval;
        }
    }

    private int nextTick = 0;

    public void Start()
    {
        this.Enabled = true;
        Interval = interval;
    }

    public void Stop()
    {
        this.Enabled = false;
    }

    public event EventHandler Callback;

    public bool Enabled = false;

    private int interval = 1000;

    public int Interval
    {
        get { return interval; }
        set { interval = value; nextTick = Environment.TickCount + interval; }
    }

    public void Dispose()
    {
        this.Callback = null;
        this.Stop();
    }

}

You can add events as follows:

Timer timer = new Timer();
timer.Callback += delegate
{
    if (once) { timer.Enabled = false; }
    Callback.execute(callbackId, args);
};

timer.Enabled = true;
timer.Interval = ms;
timer.Start();
Window.timers.Add(Environment.TickCount, timer);

To make sure the timer works, you need to create an endless loop as follows:

while (true) {
     // Create a new list in case a new timer
     // is added/removed during a callback.
     foreach (Timer timer in new List<Timer>(timers.Values))
     {
         timer.Tick();
     }
}

Comments

1

Use the PowerConsole project on GitHub or the equivalent NuGet package. It elegantly handles timers in a reusable fashion. Take a look at this sample code:

using PowerConsole;

namespace PowerConsoleTest
{
    class Program
    {
        static readonly SmartConsole MyConsole = SmartConsole.Default;

        static void Main()
        {
            RunTimers();
        }

        public static void RunTimers()
        {
            // CAUTION: SmartConsole is not threadsafe!
            // Spawn multiple timers carefully when accessing
            // simultaneously members of the SmartConsole class.

            MyConsole.WriteInfo("\nWelcome to the Timers demo!\n")

            // SetTimeout is called only once after the provided delay and
            // is automatically removed by the TimerManager class
            .SetTimeout(e =>
            {
                // This action is called back after 5.5 seconds; the name
                // of the timer is useful should we want to clear it
                // before this action gets executed
                e.Console.Write("\n").WriteError("Time out occurred after 5.5 seconds! " +
                    "Timer has been automatically disposed.\n");

                // The following statement will make the current instance of
                // SmartConsole throw an exception on the next prompt attempt
                //e.Console.CancelRequested = true;

                // Use 5500 or any other value not multiple of 1000 to
                // reduce write collision risk with the next timer
            }, millisecondsDelay: 5500, name: "SampleTimeout")

            .SetInterval(e =>
            {
                if (e.Ticks == 1)
                {
                    e.Console.WriteLine();
                }

                e.Console.Write($"\rFirst timer tick: ", System.ConsoleColor.White)
                .WriteInfo(e.TicksToSecondsElapsed());

                if (e.Ticks > 4)
                {
                    // We could remove the previous timeout:
                    //e.Console.ClearTimeout("SampleTimeout");
                }

            }, millisecondsInterval: 1000, "EverySecond")

            // We can add as many timers as we want (or the computer's resources permit)
            .SetInterval(e =>
            {
                if (e.Ticks == 1 || e.Ticks == 3) // 1.5 or 4.5 seconds to avoid write collision
                {
                    e.Console.WriteSuccess("\nSecond timer is active...\n");
                }
                else if (e.Ticks == 5)
                {
                    e.Console.WriteWarning("\nSecond timer is disposing...\n");

                    // Doesn't dispose the timer
                    //e.Timer.Stop();

                    // Clean up if we no longer need it
                    e.DisposeTimer();
                }
                else
                {
                    System.Diagnostics.Trace.WriteLine($"Second timer tick: {e.Ticks}");
                }
            }, 1500)
            .Prompt("\nPress Enter to stop the timers: ")

            // Makes sure that any remaining timer is disposed off
            .ClearTimers()

            .WriteSuccess("Timers cleared!\n");
        }
    }
}

Comments

0

Documentation

There you have it :)

public static void Main()
{
   SetTimer();

   Console.WriteLine("\nPress the Enter key to exit the application...\n");
   Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
   Console.ReadLine();
   aTimer.Stop();
   aTimer.Dispose();

   Console.WriteLine("Terminating the application...");
}

private static void SetTimer()
{
    // Create a timer with a two second interval.
    aTimer = new System.Timers.Timer(2000);
    // Hook up the Elapsed event for the timer.
    aTimer.Elapsed += OnTimedEvent;
    aTimer.AutoReset = true;
    aTimer.Enabled = true;
}

private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                      e.SignalTime);
}

1 Comment

0

I suggest you following Microsoft's guidelines.

I first tried using System.Threading; with

var myTimer = new Timer((e) =>
{
   // Code
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

But it continuously stopped after approximately 20 minutes.

With that, I tried the solutions setting:

GC.KeepAlive(myTimer)

or

for (; ; ) { }
}

But they didn't work in my case.

Following Microsoft documentation, it worked perfectly:

using System;
using System.Timers;

public class Example
{
    private static Timer aTimer;

    public static void Main()
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program at any time... ");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}
// The example displays output like the following:
//       Press the Enter key to exit the program at any time...
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM

Comments

0

You can use the StopWatch class. Here's an example:

// Create a new stopwatch class
StopWatch stopwatch = new Stopwatch();

// Start the stopwatch
stopwatch.Start();

// Wait for 10 seconds
Thread.Sleep(10000);

// Create a new timespan class and concatenate 
// it with the elapsed of the stopwatch class
TimeSpan timespan = stopwatch.Elapsed;

string time = String.Format("{0:00}:{1:00}:{2:00}",
                            timespan.Hours,
                            timespan.Minutes,
                            timespan.Seconds
);

Console.Write($"The time right now is {time}");

Console.ReadKey();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.