What is the best way to implement a timer? A code sample would be great! For this question, "best" is defined as most reliable (least number of misfires) and precise. If I specify an interval of 15 seconds, I want the target method invoked every 15 seconds, not every 10 - 20 seconds. On the other hand, I don't need nanosecond accuracy. In this example, it would be acceptable for the method to fire every 14.51 - 15.49 seconds.
4 Answers
Use the Timer
class.
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read() != 'q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
The Elapsed
event will be raised every X amount of milliseconds, specified by the Interval
property on the Timer object. It will call the Event Handler
method you specify. In the example above, it is OnTimedEvent
.

- 3,941
- 9
- 38
- 64

- 21,581
- 7
- 51
- 66
-
18
-
14@VaughanHilts, short answer, Yes. Long answer, review [this SO answer](http://stackoverflow.com/a/1436331/1630665) which explains what thread the timer elapses on very well. – Dave Zych Jan 02 '13 at 21:39
-
`OnTimedEvent` isn't being recognized on my machine. I'm using System.Timers. – shinzou Apr 22 '16 at 17:45
-
5@kuhaku `OnTimedEvent` is the method defined underneath `Main`. It's not a framework method. – Dave Zych Apr 25 '16 at 15:59
-
-
3By default Enabled is `false`. Enabled "Gets or sets a value indicating whether the Timer should raise the Elapsed event". What this means is setting it to true starts the timer, and `timer.Enabled = true;` is equivalent to calling `timer.Start()`; – Dave Zych Nov 02 '17 at 16:43
-
I've used the same MSDN documentation and I can only get this to fire once. – Daniel Jackson Feb 27 '18 at 22:36
-
Why do we need to wrap `OnTimedEvent ` in a `ElapsedEventHandler` class? I tried without the wrapper but it doesn't work. – rraallvv Mar 31 '18 at 22:24
-
-
7Caution: `System.Timers.Timer` can cause memory leaks if you don't dispose of them properly because a running timer can keep the host class "active" an prevent garbage collection on it. A good rule of thumb is if you have any class that uses one of these timers, it should implement `IDisposable` and in its `Dispose` method, you should explicitly dispose the timer(s). OR in the example above, you could add `aTimer.Dispose()` after the `Console.Read` (although admittedly, since we would be doing this at the end of `Main`, that would make no material difference in this specific example). – David Feb 12 '19 at 17:07
-
`aTimer.Interval = 5000;` does it means it will restart after `5` seconds? – Moeez Jun 03 '20 at 15:20
-
By using System.Windows.Forms.Timer
class you can achieve what you need.
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
void timer_Tick(object sender, EventArgs e)
{
//Call method
}
By using stop() method you can stop timer.
t.Stop();

- 3,638
- 2
- 28
- 35
-
1If you have one, you can just drag a timer control onto your form from the Toolbox and it does all the above for you. – Rob Sedgwick Feb 06 '14 at 20:44
-
@RobSedgwick Yes, I agree with you. we can add timer control via toolbox. But approach which i shared is via runtime add timer. – Jignesh Thakker Feb 07 '14 at 03:43
It's not clear what type of application you're going to develop (desktop, web, console...)
The general answer, if you're developing Windows.Forms
application, is use of
System.Windows.Forms.Timer class. The benefit of this is that it runs on UI
thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.
If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.

- 61,654
- 8
- 86
- 123
-
-
@Tigran, I am new to C# and I ran into exactly the same situation which you mentioned. Can you explain how can we invoke access because I am getting error of different thread for Windows Form and Timer running on different threads. Thanks – rashidkhan Dec 20 '20 at 23:18
Reference ServiceBase
to your class and put the below code in the OnStart
event:
Constants.TimeIntervalValue = 1
(hour)..Ideally you should set this value in config file.
StartSendingMails = function name you want to run in the application.
protected override void OnStart(string[] args)
{
// It tells in what interval the service will run each time.
Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
base.OnStart(args);
TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
}

- 12,864
- 16
- 78
- 107

- 1,001
- 3
- 12
- 32
-
-1 OP mentions a console app - there's no reason to bring the Windows Service classes in to this. Especially when, to solve the problem, you're using the same Timer class as the accepted answer. – TarkaDaal Aug 22 '14 at 14:13
-
5this is shown in a service but applicable to any code. NOt to mention @TarkaDaal. console is not mentioned in this post. only in the possible duplicate. – Steve Coleman Feb 25 '16 at 19:35
-
16 years late, But I might as well mention this answer is using "System.Threading.Timer" meanwhile the accepted answer is using "System.Timers.Timer". so it's not the same Timer class. – Pedram Oct 28 '20 at 13:36