Reputation: 157
I write a Windows Service in .Net Framework 4.0 and I need to schedule a recurring task inside. New task can only run if previous one is finished, so no tasks in parallel... All my task occurences work on same object (WCF Channel factory). A task takes almost 2 seconds to complete and may be scheduled every 2 seconds or every hour. My constraint is to have this Windows service as invisible/light as possible on memory and processor uses point of view...
I've already found these 2 ways:
System.Timers.Timer
with Autoreset
to false => I've to
implement an ElapsedEventHandler
and pass my shared object (WCF
Channel factory)Any suggestions?
Thanks and have a nice day!
Upvotes: 2
Views: 13931
Reputation: 4881
For me was fine following: I'm started timer once, then in Tick method I will schedule next Tick call. Like this:
private Timer _timer;
//Interval in milliseconds
int _interval = 1000;
public void SetTimer()
{
// this is System.Threading.Timer, of course
_timer = new Timer(Tick, null, _interval, Timeout.Infinite);
}
private void Tick(object state)
{
try
{
// Put your code in here
}
finally
{
_timer?.Change(_interval, Timeout.Infinite);
}
}
// dont forget to dispose your timer using await _timer.DisposeAsync(); or _timer.Dispose();
Upvotes: 3
Reputation: 1095
System.Timers.Timer
is the way to go and will have little to no system performance impact. Current systems can handle thousands of timers.
Since you want the timer to continue, don't set AutoReset, but you will need a way to change its interval (if that's what you need).
Your service instance should hold an instance of your WCF channel factory.
To ensure synchronous processing, you should implement an Interlocked
protected flag, like a long, which can serve as an indicator of busyness. If equal to one, for example, the method that kicks off processing from timer elapsed event will simply return. Once processing is complete, at which time you set the flag to zero, further timer elapsed events will be able to enter and kick off processing again.
Remember to stop, restart, and dispose of your timer in the various service events, like pause, stop, start.
Upvotes: 1