Timers are pretty useful. They allow you to define a block of code that will execute on a given interval. It’s the C# version of JavaScript’s setInterval. There’s a lot of different reasons for using a timer, such as persisting updates to a database. Since database calls can be slow, maybe you want to build up a list of changes and then commit them every 30 seconds.
A better timer
In the example above, I am persisting updates to a database on a timer. This means that the changes will be accrued for 30 seconds (or whatever interval you specify), and then sent to the database to be persisted. However, if you have a lot of changes, you could end up taking longer than 30 seconds … and then the timer elapses again, and you start another update process. If this process continues, you could choke out your database and send your entire app spiraling to a crawl.
Enter the TimedProcessor
I made the TimedProcessor as a way to alleviate this issue. In our use case, we want the updates to happen regularly – but if the operation takes awhile to complete, we don’t want to kill the rest of our application. The TimedProcessor will only execute its action one-at-a-time. Effectively, it just turns the AutoReset of the internal timer off, and then turns the timer back on when the action is finished. Note that this also means the timer is going to wait the interval you specify before firing the action again – thus giving your application a little bit of breathing room.
Here’s the code:
I also put it on GitHub with some unit tests around it.