2

I use two System.Windows.Forms.Timer objects in my project as below.

private void Form1_Load(object sender, EventArgs e)
{
    timer1.Interval = 60000;
    timer2.Interval = 62000;
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    Console.WriteLine("Timer1 :" + DateTime.Now.ToString());
    timer2.Start();
}

private void timer2_Tick(object sender, EventArgs e)
{  
    Console.WriteLine("Timer2 :" + DateTime.Now.ToString());
    timer2.Stop();
}

The output result is :

Timer1 :05/30/2011 12:15:57 AM      (12:16:59)
Timer1 :05/30/2011 12:16:57 AM      (12:17:59) miss
Timer2 :05/30/2011 12:16:59 AM      

Timer1 :05/30/2011 12:17:57 AM      (12:18:59)
Timer1 :05/30/2011 12:18:57 AM      (12:19:59) miss
Timer2 :05/30/2011 12:18:59 AM

Timer1 :05/30/2011 12:19:57 AM      (12:20:59)
Timer1 :05/30/2011 12:20:57 AM      (12:21:59) miss
Timer2 :05/30/2011 12:20:59 AM

I can't understand why every second time of timer1 for timer2 is missing.

I mean Timer2 should start at 12:17:59 for Timer1 start at 12:16:57 AM.

How can I change it to get the right algorithm?

0

4 Answers 4

5

I'm not sure why you are doing this, but it is working as you designed. When timer1 ticks, it outputs a message and turns on timer2. Then timer1 ticks again but timer2 is already on so nothing happens there. Then timer2 ticks and turns off. That is why you are getting two timer1s for every timer2. Timer2 is already running the second time you try to turn it on.

If you really want this to work right, you will probably need to add a third timer and then alternate between the two. Check to see if timer2 is running, and if it is, start timer3. Otherwise start timer2.

3

Timer.Start() does nothing if the timer is already Enabled. It's not some kind of a "Restart". So, the timer2.Start() at 12:16:57 does nothing.

3

What pattern are you actually trying to achieve with the timers? Try drawing a timing diagram showing each event and the delays between them. The output is as expected: Timer2 fires 2 seconds after the second Timer1 tick since it started at the same time as Timer1 which only ran for 60s.

2

You're restarting the timer2 every time timer1_Tick event occurs so use this:

private bool timer2Started;
private void timer1_Tick(object sender, EventArgs e)
{
    Console.WriteLine("Timer1 :" + DateTime.Now.ToString());
    if (!timer2Started) { timer2.Start(); timer2Started = true; }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.