Question

I've been looking into the Timer class (http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx), but the thing about the timer is, it's on going. Is there a way to stop it after one go? or after 5 go's?

Right now i am doing the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

namespace TimerTest
{
    class Program
    {
        private static System.Timers.Timer aTimer;
        static void Main(string[] args)
        {
            DoTimer(1000, delegate
            {
                Console.WriteLine("testing...");
                aTimer.Stop();
                aTimer.Close();
            });
            Console.ReadLine();
        }

        public static void DoTimer(double interval, ElapsedEventHandler elapseEvent)
        {
            aTimer = new Timer(interval);
            aTimer.Elapsed += new ElapsedEventHandler(elapseEvent);
            aTimer.Start();
        }
    }
}
Was it helpful?

Solution

It is not on going the way you have it now. The Elapsed event is raised once and stops because you have called Stop. Anyway, change your code like the following to accomplish what you want.

private static int  iterations = 5;
static void Main()
{
  DoTimer(1000, iterations, (s, e) => { Console.WriteLine("testing..."); });
  Console.ReadLine();
}

static void DoTimer(double interval, int iterations, ElapsedEventHandler handler)
{
  var timer = new System.Timers.Timer(interval);
  timer.Elapsed += handler;
  timer.Elapsed += (s, e) => { if (--iterations <= 0) timer.Stop(); };
  timer.Start();
}

OTHER TIPS

Why don't you just have an int counter that initially start out at 0 and is incremented every time the ElapsedEventHandler is fired? Then you simply add a check in the event handler to Stop() the timer if the counter exceeds the number of iterations.

Use System.Threading.Timer and specify a dueTime but specify a period of Timeout.Infinite.

public static void DoTimer(double interval, ElapsedEventHandler elapseEvent)
{
    aTimer = new Timer(interval);
    aTimer.Elapsed += new ElapsedEventHandler(elapseEvent);
    aTimer.Elapsed += new ElapsedEventHandler( (s, e) => ((Timer)s).Stop() );
    aTimer.Start();
}

By creating object of given class you can use timer in any class

public class timerClass
    {


        public timerClass()
        {
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            // Set the Interval to 5 seconds.
            aTimer.Interval = 5000;
            aTimer.Enabled = true;
        }

        public static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
          Console.Writeln("Welcome to TouchMagix");
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top