C # timer class - stop after a certain number of fires
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 what happens. Is there a way to stop it after one? or after 5 go?
I am currently 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();
}
}
}
This is not how it is now. The Elapsed event is raised once and stops because you called Stop. Anyway, change your code as follows 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();
}
Why don't you just have a counter int
that initially starts at 0 and increments each time it starts up ElapsedEventHandler
? Then you just add an event handler check to the Stop()
timer if the counter exceeds the number of iterations.
Use System.Threading.Timer and specify the timeout but specify the period as 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 an object of this class, you can use a 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");
}
}