Click here to Skip to main content
Click here to Skip to main content

Pre-beginner's guide to using a timer

By , 15 Mar 2002
 

Introduction

This is my first C# article in a long time. A couple of days ago, Paul Watson was chatting with me on Sonork and he suddenly mentioned that in VB he used to use some function called Now() which used to give him the current date and time instantly. He was complaining that he couldn't find the corresponding .NET function. That's when I did a quick check and discovered the DateTime class or rather structure.

Of course this article is not about the DateTime structure. I suddenly wondered how to use timer based procedures from C#. We all use SetTimer once in a while when we code and it struck me as odd that I never wondered about this in C#. Luckily I had that new Petzold book and Chapter 10 was dedicated to timers and time related functions. Just one page on timers though, though to be fair to him, that was all that was needed. I then played around with it a little.

This article will simply show you how to use them, though if you have the Petzold book that's all you need really. I am also including as an example project, a program that will wait on you and keep popping up a reminder Yes/No message at the time interval you specify, till you click on Yes.

Using Timers

We use the System.Windows.Forms.Timer class for our timer purposes. First we need to create a Timer object. Then we need to set the timer interval. This is accomplished as follows :-

Timer timer01 = new Timer();
timer01.Interval = 1000;

The Timer class has a Tick event. That's exactly what we needed eh? We add our timerproc as our Timer object's event handler as follows :-

timer01.Tick += new EventHandler(timerproc);

Then we simply enable the timer.

timer01.Enabled = true;

That's it. Now every 1000 milliseconds [cause that's the amount we specified], the timerproc gets called.

The timer proc

Within our form class we'll need a function like this :-

void timerproc(object o1, EventArgs e1)
{
	//blah blah blah
	//blah blah blah
	//blah blah blah
}

Say, you want to close the timer after some time. Then you can do this :-

((Timer)o1).Stop();
((Timer)o1).Tick -= new EventHandler(timerproc);

Before I sign off I better tell you how to get the current time, since that's how this whole article got started :-)

DateTime.Now.ToLongTimeString();

Now people like Paul won't complain that .NET is tougher than VB ;-)

Conclusion

I am fully aware of the enormously high flame potential this article has and that it is a pre-beginner level thing that I have explained here. But I was quite delighted when I got the timer working and I thought there might be other idiots like me who would be similarly happy. And I simply could not resist the temptation to write another CP article, specially since I have temporarily ceased work on my planned Winsock series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nish Sivakumar
United States United States
Member
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionGreat article !memberWrangly15 Aug '11 - 23:37 
Great article ! my vote is max !!
 
Tkx,
Domi.
GeneralMy vote of 5memberM Bester2 Feb '11 - 23:27 
Easy to understand
QuestionHow to make a timer?member3nity6 Sep '08 - 7:13 
Is is possible to do a timer?
I have a function that I want to measure the actual time for calling the function till the end of the function.
I hope you know what I mean and thank you for the answer.
Questiontimer won't firememberc-a-b-6 Apr '06 - 5:31 
I'm hoping someone can help me figure out why my timer won't fire. I have a notify form that I want to fade over time. When the form is displayed it starts a timer and then every tick it fades a bit until it disappears and then is closed. This all works from from my main thread. The problem is, I also want to use this method from an event handler. Unfortunately, when I show the notify window from the event handler, the timer does not start. Since I invoke the notify window exactly the same in both cases, I suspect that there is something special about the event handler. Any ideas?
 
Oh by the way, the event handler is called when someone writes an error to the system event log (just in case that is relevant)
 
Caralyn
GeneralTick Event ProblemsussAnonymous4 Dec '03 - 17:38 
Hi! I am creating an application wherein it would automatically refresh its content (which is pulled from a database) after a predetermined time. The problem I am experiencing is that once Application.Run is invoked, I couldn't do a refresh without raising an event like clicking a button. I want to invoke Timer.enabled only after the form is shown. Any help on this matter will be greatly appreciated. Thanks!
GeneralScreenShotmemberColin Davies19 Mar '02 - 18:06 
Nise ScreenShot Nish Smile | :)
 
Regardz
Colin J Davies


Sonork ID 100.9197:Colin
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()"> Jig | [Dance] Jig | [Dance] Jig | [Dance] </marquee>
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()" direction = "right">Jig | [Dance] Jig | [Dance] Jig | [Dance] </marquee>
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()"> Jig | [Dance] Jig | [Dance] Jig | [Dance]

GeneralRe: ScreenShotmemberNish [BusterBoy]19 Mar '02 - 18:11 
Thanks Colin.
I am on XP.
 
Smile | :)
 
The screenshot was made on XP.
 
How abt you?
What's your basic OS now?
 
Nish
 

My miniputt high is now 29
I do not think I can improve on that
My temperament won't hold
 
www.busterboy.org


GeneralRe: ScreenShotmemberColin Davies19 Mar '02 - 18:21 
Nish [BusterBoy] wrote:
The screenshot was made on XP.
 
How abt you?
What's your basic OS now?

 
I could tell it was XP by the theme thingy,
 
I just moved to Win-2000, and am impressed by its stability.
 
Regardz
Colin J Davies


Sonork ID 100.9197:Colin
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()"> Jig | [Dance] Jig | [Dance] Jig | [Dance] </marquee>
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()" direction = "right">Jig | [Dance] Jig | [Dance] Jig | [Dance] </marquee>
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()"> Jig | [Dance] Jig | [Dance] Jig | [Dance]

GeneralRe: ScreenShotmemberNish [BusterBoy]19 Mar '02 - 18:30 
Colin Davies wrote:
I just moved to Win-2000, and am impressed by its stability
 
Well, XP is just as stable as Win2K and looks better, once you get used to it. The first 2 days, it looks too fancy for professional use. But then you get to like it.
 
Nish
 

My miniputt high is now 29
I do not think I can improve on that
My temperament won't hold
 
www.busterboy.org


GeneralRe: ScreenShotmemberTim Smith20 Mar '02 - 2:58 
The first 2 days, it looks too fancy for professional use.
 
says in his best lumberjack voice XP UI is for girly men!!!!.
 
Smile | :)
 
Tim Smith
 
I know what you're thinking punk, you're thinking did he spell check this document? Well, to tell you the truth I kinda forgot myself in all this excitement. But being this here's CodeProject, the most powerful forums in the world and would blow your head clean off, you've got to ask yourself one question, Do I feel lucky? Well do ya punk?
GeneralRe: ScreenShotmemberNish [BusterBoy]20 Mar '02 - 3:23 
Tim Smith wrote:
XP UI is for girly men!!!!.
 
Yeah, maybe...
 
Nish
 

My miniputt high is now 29
I do not think I can improve on that
My temperament won't hold
 
www.busterboy.org


GeneralAdditionally,memberDavid Wengier18 Mar '02 - 0:25 
From VB you could use Date() and Time() to get the respective values.
 
They are now DateTime.Today and DateTime.TimeOfDay respectively Smile | :)
 
In fact (in VB.NET at least) you dont need the "DateTime" prefix because Now is defined in the Microsoft.VisualBasic namespace as well, so you dont even need to change your code (in my experience at least)
 
--
David Wengier
 
Sonork ID: 100.14177 - Ch00k
GeneralRe: Additionally,memberNish [BusterBoy]18 Mar '02 - 0:42 
Oh, thanks Smile | :)
I haven't tried out VB .NET yet...
 
Nish
 
p.s. Paul W has migrated to C# and I don't think he's planning to do any VB .NET
 

My miniputt high is now 29
I do not think I can improve on that
My temperament won't hold
 
www.busterboy.org


GeneralWelcome!memberMazdak16 Mar '02 - 5:15 
Nish,Welcome to the C# world!Big Grin | :-D
 
<html>Mazy</html>
 
"So,so you think you can tell,
Heaven from Hell,
Blue skies from pain,...
How I wish,how I wish you were here."
Wish You Were Here-Pink Floyd-1975


GeneralRe: Welcome!memberNish [BusterBoy]17 Mar '02 - 14:04 
Thanks Mazy. This is my 2nd jump actually Smile | :)
 
Nish
 

My miniputt high is now 29
I do not think I can improve on that
My temperament won't hold
 
www.busterboy.org


GeneralGood ArticlememberNick Parker16 Mar '02 - 1:44 
Nish,
Good article, don't worry about the rating, I had similar feelings when I wrote: Creating Your First C# Windows Application. Maybe we should consider talking to Chris about creating a section of good code sniplets that people would like to share.
 
Nick Parker

GeneralRe: Good ArticlememberNish [BusterBoy]16 Mar '02 - 3:12 
Thanks Nick.
Yeah a section called code snippets or sniplets as you say would be useful. Since we already have a bugs section, we might as well have this one too Smile | :)
 
Nish
 

My miniputt high is now 29
I do not think I can improve on that
My temperament won't hold
 
www.busterboy.org


GeneralRe: Good ArticlememberChris Maunder16 Mar '02 - 8:36 
I've thought long and hard about that but my personal feeling is that people, in general, take the path of least resistance. I'd rather force people write at least a couple of paragraphs explaining what they've done (how long can that take? 5 minutes?) than create a junk yard of unidentifiable code snippets.
 
That said, Paul Watson volunteered a while ago to write a code snippet system that would combine the best of both worlds. I'm sure he has thought (hoped) that I'd forgetten all about that Big Grin | :-D

 
cheers,
Chris Maunder
GeneralRe: Good ArticlememberNish [BusterBoy]17 Mar '02 - 14:05 
Chris Maunder wrote:
That said, Paul Watson volunteered a while ago to write a code snippet system that would combine the best of both worlds
 
Yeah, I remember that. He said he had tons of javascript snippets to submit and that he'd maintain it and stuff. Then very smartly he's kept quiet Wink | ;-)
 
Nish
 

My miniputt high is now 29
I do not think I can improve on that
My temperament won't hold
 
www.busterboy.org


GeneralRe: Good ArticlememberColin Davies19 Mar '02 - 18:10 
Nish [BusterBoy] wrote:
Then very smartly he's kept quiet
 
Yes, Now he's showing real intelligence Smile | :)
Like in the Army when they ask for volunteers to step-forward.
Shuffle backwards real quickly. Smile | :)
 
Regardz
Colin J Davies


Sonork ID 100.9197:Colin
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()"> Jig | [Dance] Jig | [Dance] Jig | [Dance] </marquee>
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()" direction = "right">Jig | [Dance] Jig | [Dance] Jig | [Dance] </marquee>
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()"> Jig | [Dance] Jig | [Dance] Jig | [Dance]

GeneralRe: Good ArticlememberNish [BusterBoy]19 Mar '02 - 18:14 
Colin Davies wrote:
Like in the Army when they ask for volunteers to step-forward.
Shuffle backwards real quickly

 
LOL
 
That's sure smart Smile | :)
 
Nish
 

My miniputt high is now 29
I do not think I can improve on that
My temperament won't hold
 
www.busterboy.org


GeneralRe: Good ArticlememberColin Davies19 Mar '02 - 18:19 
Nish [BusterBoy] wrote:
That's sure smart
 
Its True Nish ! Smile | :)
Don't you guys have National service ?

 
Regardz
Colin J Davies


Sonork ID 100.9197:Colin
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()"> Jig | [Dance] Jig | [Dance] Jig | [Dance] </marquee>
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()" direction = "right">Jig | [Dance] Jig | [Dance] Jig | [Dance] </marquee>
<marquee behavior="alternate" scrollamount ="7" onmouseover="stop()" önmouseout ="start()"> Jig | [Dance] Jig | [Dance] Jig | [Dance]

GeneralRe: Good ArticlememberNish [BusterBoy]19 Mar '02 - 18:24 
Colin Davies wrote:
Don't you guys have National service ?
 
Dunno.
I think there is something called NCC [National Cadet Corps] but that's for kids.
 
Nish
 

My miniputt high is now 29
I do not think I can improve on that
My temperament won't hold
 
www.busterboy.org


General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 16 Mar 2002
Article Copyright 2002 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid