Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

Use System.Threading.Timer or Quartz in an ASP.NET

I want my ASP.MVC application to function as a scheduler for background tasks. The HttpApplication-subclassed class has the following code:

public class MvcApplication : System.Web.HttpApplication
{
    private Timer Timer;
    protected void Application_Start()
    {
        if (Timer == null)
        {
            TimerCallback cb = OnTimerElapsed;
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            Timer = new Timer(cb, autoEvent, INITIAL_DELAY, TIMER_INTERVAL);
        }
    }

    private void OnTimerElapsed(Object stateInfo)
    {
        //perform background task
    }
}

In addition, instead of using System.Threading.Timer, I also replace it by Quartz-equivalent code, but it also stops firing after a while.

So this begs the question, is Application_Start() the right place or is there a better place?

Both Timer and Quartz approaches work. But with Quartz, it seems like for an interval of 1 minute, after 20 intervals (20 minutes), the trigger no longer fires. With Timer, I am not sure after how many intervals that the trigger stops firing.

Upvotes: 1

Views: 2288

Answers (2)

Robin Rieger
Robin Rieger

Reputation: 1194

(Note: I release this is way late this answer but for anyone stumbling over this my two cents are below)

The reason for the 20min thing sounds like iis idle timeout... the default is 20 minutes.

Try changing the idle timeout in the app pool (advanced settings) from 20 to 0. I had a similar problem with some queue stuff I was working with. This change should make the app stay up and the timer stuff running.

Upvotes: 1

Eric J.
Eric J.

Reputation: 150138

ASP.Net is not the platform of choice for long-running or periodic-running processes like you are describing, though I'm not sure specifically why your timers stop firing.

However, here's a post by someone that wanted to accomplish almost the same thing that outlines his approach:

http://www.west-wind.com/weblog/posts/2007/May/10/Forcing-an-ASPNET-Application-to-stay-alive

Upvotes: 0

Related Questions