Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many System.Timers.Timer instances can I create? How far can I scale?

Tags:

.net

timer

I have an application which makes use of System.Timers.Timer objects to do expirations and email notifications and such. Currently the system has a couple hundred timers alive at once, but we are going to be expanding the usage of the app and that number might start scaling into the thousands (probably no higher than 10,000).

I can't find any information on scaling up the number of Timers so I assume it is not going to be a problem. Does anyone know if this is going to be a problem and I should proactively look into changing the way I handle the expirations?

like image 804
tster Avatar asked Jun 23 '10 15:06

tster


2 Answers

A little late on this, I know, but . . .

System.Timers.Timer is a wrapper around System.Threading.Timer, which in turn is a .NET wrapper around Windows' Timer Queues. Timer queue timers are very lightweight--use few system resources. I've not scaled to thousands of timers, but hundreds of timers works just fine. From what little I've been able to glean of the implementation, I can't imagine that there would be any trouble with thousands of timers.

There's probably some limit on the number of timers you can have in any particular timer queue. I don't know what that limit is. When I investigated these timers a year or so ago, it looked like the .NET Framework creates one timer queue per process (or maybe it was per app domain), and all the timers you create are put into that one queue.

It probably doesn't make sense to duplicate the timer queue functionality by creating your own system that uses a single timer and some type of priority queue mechanism to control what's called next. That's what the timer queue does for you already.

It seems like you could easily build a test program that creates 10,000 timers. Set each one to tick one second after the last, and set its period to 10,000 seconds. Then sit back and watch it tick. Or have your program keep track of who should tick next and who actually ticks next.

like image 74
Jim Mischel Avatar answered Nov 01 '22 14:11

Jim Mischel


Isn't it better to use one timer only? This timer fires e. g. every second or every minute and then you compare DateTime.Now() to the Setpoint DateTime objects of your Schedule Plan. If Setpoint DateTime object matches DateTime.Now(), fire an event and recalculate the next execution DateTime for your object.

like image 40
brighty Avatar answered Nov 01 '22 13:11

brighty