# Simple Timers in C#



## Kreij (Jan 14, 2011)

I don't think I've done a post on simple timers before.
If I did then consider this a refresher.

A timer is simply a process that you start that fires an event when a certain amount of time (interval) has passed. They can be very useful for lots of things. You could use one to run a clock, notify the user that they have been on the computer too long or in our case to check your beer for fluid volume depletion. 

Anyway ... Here we go.
To create a timer, just instantiate a timer.
(Note : We are using the Timer class in System.Windows.Forms.Timer ... not the other timers available in other namespaces. That's why it's called simple timers. This one has very limited access to methods)

```
Timer _CheckYourBeer = new Timer();
```
Cool. We have a timer. It's not very useful. We need to give it something to do.
We do this by assigning and event handler to the timer.

```
Timer _CheckYourBeer = new Timer();
_CheckYourBeer.Tick += new EventHandler(_CheckYourBeer_Tick);
```
A timer Tick is what the timer does when it decides it's time to do something. 
Awesome. We now have assigned it an event handler so all we have to do is create the event handler. Piece of cake ...

```
void _CheckYourBeer_Tick (object sender, EventArgs e)
{
    this.Text = "Check Your Beer";
}
```
Yay ! Our event handler will now change the title bar of the form to read "Check Your Beer".
Wait !! We need to tell the timer how often we want it to remind us. We do this by setting the timer's interval value (in milliseconds). This is the amount of time to wait before firing the Tick event.

```
Timer _CheckYourBeer = new Timer();
_CheckYourBeer.Tick += new EventHandler(_CheckYourBeer_Tick);
_CheckYourBeer.Interval = 300000;
```
We are pretty serious about checking the beer so we have set the timer to fire every 5 minutes. For you more serious drinkers, I would recommend every minute (interval=60000).

Now to start the timer working, we just need to tell it to start.

```
Timer _CheckYourBeer = new Timer();
_CheckYourBeer.Tick += new EventHandler(_CheckYourBeer_Tick);
_CheckYourBeer.Interval = 300000;

_CheckYourBeer.Start();
```

You will need some way to let the program know that you checked the beer, so in this case you will need a button or something you can click to set the form title back to something else.
You may also want a button called "IveHadEnough" to stop the timer. (I can't really relate to this, but....)

To stop the timer, just put the following line in the IveHadEnough buttons click event handler.

```
_CheckYourBeer.Stop();
```

That's it's. Hope this little snippet helps someone.
As always questions and comments are always welcome.
Cheers and happy coding.


----------

