18

I want to use a timer in my simple .NET application written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console application.

Is there a C# timer (or timer like) class for use in console applications?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MrDatabase
  • 43,245
  • 41
  • 111
  • 153

6 Answers6

29

System.Timers.Timer

And as MagicKat says:

System.Threading.Timer

You can see the differences here: http://intellitect.com/system-windows-forms-timer-vs-system-threading-timer-vs-system-timers-timer/

And you can see MSDN examples here:

http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx

And here:

http://msdn.microsoft.com/en-us/library/system.threading.timer(VS.80).aspx

Lockszmith
  • 2,173
  • 1
  • 29
  • 43
albertein
  • 26,396
  • 5
  • 54
  • 57
  • 2
    This does answer the question, but talk about "minimal". Spoon's answer is much better. – OJ. Oct 03 '08 at 23:49
15

I would recommend the Timer class in the System.Timers namespace. Also of interest, the Timer class in the System.Threading namespace.

using System;
using System.Timers;

public class Timer1
{
    private static Timer aTimer = new System.Timers.Timer(10000);

    public static void Main()
    {
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true;

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

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

Example from MSDN docs.

Eric Schoonover
  • 47,184
  • 49
  • 157
  • 202
8

There are at least the System.Timers.Timer and System.Threading.Timer classes that I'm aware of.

One thing to watch out though (if you haven't done this before already), say if you already have the System.Threading namespace in your using clause already but you actually want to use the timer in System.Timers, you need to do this:

using System.Threading;
using Timer = System.Timers.Timer;

Jon Skeet has an article just on Timers in his multithreading guide, it's well worth a read: https://jonskeet.uk/csharp/threads/timers.html

N3pp
  • 33
  • 1
  • 4
theburningmonk
  • 15,701
  • 14
  • 61
  • 104
-1

This question is old and existing answers cover well the issue as it was at the time. In the meantime, something new has happened.

Timer, sure, for what ?

Using a timer is a way to run some processing with some delay and/or at regular interval. There are two cases:

(1) it's just to run some short code periodically without any thread concern, no trouble, no mess. If the plain Windows Forms timer is not suitable, then System.Timers.Timer with its SynchronizingObject property makes it more straightforward than System.Threading.Timer .

(2) what you're coding is in the realm of asynchronous concurrent processing. That has traditionally been error-prone, difficult to debug, to get right, whatever the plain timer used.

In case 2 you might get away with traditional approach, but beware, complexity is lurking and ready to eat you not just once but any time you just don't make the best choice, with cumulative effects.

Now we've got something better

If your situation deals with some kind of "event" handling (whatever the way it's coded: keypresses, mouse buttons, bytes from a serial port, from a network connection, from measurements, etc), you should consider Reactive Programming.

Reactive Programming has in recent years somehow uncovered how to code for these situations, while not falling into complexity traps.

So, technically the following link is an answer to the question: it is a timer which is in the System.Reactive.Linq namespace: Observable.Timer Method (System.Reactive.Linq)

To be fair, it's a timer that comes and plays well with the Reactive Programming mindset and a lot of game-changing stuff. Yet it might or might not be the best tool, depending on the context.

Since this question is .NET-centric, you might be interested in Good introduction to the .NET Reactive Framework

Or for a clear, illustrated, more general (not Microsoft-centric) document, this seems good The introduction to Reactive Programming you've been missing.

Community
  • 1
  • 1
Stéphane Gourichon
  • 6,493
  • 4
  • 37
  • 48
  • A comment with the link to reactive framework introduction would suit better as a hint to OP/future readers than the answer like this. – Sinatr Aug 04 '20 at 10:23
  • @Sinatr I don't understand your rationale, can you elaborate? The first part answers the question as asked, so it's an actual answer. As a bonus, the second part hints at other tools that may solve a possible instance of the famous "[XY problem](http://xyproblem.info/)". Do you mean that the second part invalidates the whole answer? What do you mean? – Stéphane Gourichon Aug 07 '20 at 20:55
  • Imho. Too many words and links to support another technology. Which should rather be posted in question "How reactive framework is better than X" or similar. Imagine a question about A and answer "don't do A, do B". Unless you clearly identified XY problem (here we don't, console application and timers totally ok), you shouldn't be answering like this 7 years after question was asked. If you would mention X in comments and OP reply "This looks promising, can you tell me more about X and my problem?", then answer would be more justified (you could quote OP comment in answer). – Sinatr Aug 10 '20 at 07:07
  • Zero upvotes over 5 years proves my point somehow, aren't they? – Sinatr Aug 10 '20 at 07:10
  • Thanks @Sinatr. I think I get your first comment now. I agree that the second part of my answer kind of "hides"/"dilutes" the first. The first part still added something to the conversation, where I recommend `System.Timers.Timer` over `System.Threading.Timer`. Is that enough to click on "Not useful"? Anyway, after 5 years my StackExchange practice improved. I guess the case is settled and we all make progress. Thanks again for explaining. – Stéphane Gourichon Aug 11 '20 at 08:58
-2

System.Diagnostics.Stopwatch if your goal is to time how long something takes to run

DaveK
  • 4,509
  • 3
  • 33
  • 33
-2

It is recommended to not to use System.Timer's Timer class.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
Sucharit
  • 5
  • 1