Background: I have a .NET 4.0 web service running on Windows Server 2008 written in C#. I would like to run a timer inside the asp.net web service that runs code once a day. I have heard of some limitations with this (see below) but I am asking if what I plan is OK in order to get around some of the limitations and to keep the code inside the web service as it is not mission critical code. However a crash is unacceptable. Note: I am not and can not use WCF.
The plan:
- Declare and instantiate
System.Threading.Timer
in the constructor of my web service (right next to the commented out line://InitializeComponent();
). - Fire timer every 30 minutes.
- Note: Because I am using
System.Threading.Timer
I should not have to run keep-alive code according to msdn Tip #6 below. - IF the current time is within 30 minutes of my database value (desired time to run code) THEN run code.
Questions:
- I would like to know how reliable it is to use
System.Threading.Timer
in asp.net c# code using the plan above and if it would run correctly let’s say more than 97% of the time? - Will this plan work when the app pool is recycled and when IIS server is restarted?
It seems there are issues using timers in web services with regards to:
- app pool recycling
- threads dying
- no one hits web for a long period
- of time memory issues (better to use windows service)
References:
ASP.NET Site - Firing some code at a specific time
Timer on Website to activate Web Service calls every hour
http://forums.asp.net/t/1079158.aspx/1
http://msdn.microsoft.com/en-us/magazine/cc163854.aspx (see Tip #6)
From Tip #6 “The Timer class, found in the System.Threading namespace, is a wonderfully useful, but less well-known class in the .NET Framework, at least for Web developers. Once created, the Timer will invoke the specified callback on a thread from the ThreadPool at a configurable interval. This means you can set up code to execute without an incoming request to your ASP.NET application, an ideal situation for background processing. You can do work such as indexing or sending e-mail in this background process too.”