Pomster
Pomster

Reputation: 15197

Can I use Timer with no Timer Component?

I'm working with a windows service and they are so hard to test, so would like to leave it as a empty as possible only importing classes.

I need to use a Timer to trigger and event every 5 minutes, but if i use the timer component i have to place it on my windows service.

So is it possible to build my own basic timer class ??

How would i go about this? i want to to be very small and light, a few lines of code if possible.

Upvotes: 1

Views: 125

Answers (3)

ABH
ABH

Reputation: 3439

You can use System.Timers.Timer or System.Threading.Timer

From MSDN

// Create a timer with a ten second interval.
System.Timers.Timer aTimer = new System.Timers.Timer(10000);

// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;

Timer elapsed event handler

// Specify what you want to happen when the Elapsed event is 
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}

You wont be requiring timer component in this case

Here is the complete article on Timers in .Net. Complete comparison between different type of timers is discussed here.

Upvotes: 5

Martin James
Martin James

Reputation: 24867

Thread.Sleep(1000*60*5); // filler because my answer is too small and light otherwise.

.. or, to make it more 'Timer-ish' add a for loop:

for(;;){
  timerEvent();
  Thread.Sleep(1000*60*5);
};

Upvotes: 0

Martin Moser
Martin Moser

Reputation: 6269

Have you checked System.Threading.Timer or System.Timers.Timer ? That should be what you are looking for.

Upvotes: 2

Related Questions