views:

24

answers:

1

Hi,

I am trying to implement a reoccurring timer function asp.net. I am not able to create a windows service as I host the site on a shared environment and therefore do not have access.

I have read various ways of achieving this each with their own advantages/disadvantages. The cache object approach seemed promising but does seem like a hack.

I have been trying to implement a httphandler that will spin up a single System.Threading.Timer object to cycle every minute and do some work. Possibly queuing up other work items.

Here is what I have so far:

public class Scheduler : IHttpHandler
{
    protected static TimerCallback tcb = null;
    protected static Timer timer = null;

    static Scheduler()
    {

        tcb = new TimerCallback(DoWork);
        timer = new Timer(tcb, null, TimeSpan.Zero, new TimeSpan(0, 0, 1, 0));
    }

    private static void DoWork(Object stateInfo)
    {
    }

    public void ProcessRequest(HttpContext context)
    {

    }

    public bool IsReusable
    {
        get { return false; }
    }

}

I read here that you need to mindful of the timer not being disposed of when the appDomain unloading. He does imply that it is only a problem if you are invoking native code which I am not. I couldn't figure out how to tie into the application_end event to dispose of the timer from within the handler.

My question is, Is the above approach way off the mark? Is there a better way to do this? Would it make more sense to ditch the static variables and store the timer in application state?

Sorry I need informed opinions. I feel like i'm going around in circles.

Thanks,

+1  A: 

This is a complete hack, hope I don't get down voted! - but you could develop a component which is part of your web deployment which makes an Http request to a handler on the same site - this way (I guess) your app would be able to call itself to ensure it wasn't unloaded. see the WebClient class - sorry not sure which namespace off the top of my head.

If you do this you'll need to think about how it's restarted if it's taken down for any reason; and I'm not sure if you'll get any weird behaviour if you have a web application that stays up for really long periods of time.

Adrian K