Simulate a Windows Service Using ASP.NET to Run Scheduled Jobs

by Bill Beckelman 20. September 2008 12:42

Back in 2005 Omar Al Zabir (Co-founder and CTO of PageFlakes) posted an article on the CodeProject web site Simulate a Windows Service using ASP.NET to run scheduled jobs that many of you have probably seen. If you liked the idea at the time but didn't do anything with it, you may want to take another look now. In the comments, dselkirk provided an alternative that really cleans things up that Erichero then improved upon slightly and converted to C#.

The code from the comments is below. I can confirm it works. I have not modified it in any way. All credit goes to Omar, dselkirk and Erichero.

public class Scheduler
{
    private class CacheItem
    {
        public string Name;
        public Callback Callback;
        public Cache Cache;
        public DateTime LastRun;
    }

    public delegate void Callback();

    private static int _numberOfMinutes = 1;

    public static void Run(string name, int minutes, Callback callbackMethod)
    {
        _numberOfMinutes = minutes;
        
        CacheItem cache = new CacheItem();
        cache.Name = name;
        cache.Callback = callbackMethod;
        cache.Cache = HttpRuntime.Cache;
        cache.LastRun = DateTime.Now;
        AddCacheObject(cache);
    }

    private static void AddCacheObject(CacheItem cache)
    {
        if (cache.Cache[cache.Name] == null)
        {
            cache.Cache.Add(cache.Name, cache, null,
                 DateTime.Now.AddMinutes(_numberOfMinutes), Cache.NoSlidingExpiration,
                 CacheItemPriority.NotRemovable, CacheCallback);
        }
    }

    private static void CacheCallback(string key, object value, CacheItemRemovedReason reason)
    {
        CacheItem obj_cache = (CacheItem) value;
        if (obj_cache.LastRun < DateTime.Now)
        {
            if (obj_cache.Callback != null)
            {
                obj_cache.Callback.Invoke();
            }
            obj_cache.LastRun = DateTime.Now;
        }
        AddCacheObject(obj_cache);
    }
}

Example usage (code goes in the Aplication_Start event in Global.asax)

Scheduler.Run("test", 1, RunScheduledTasks);
public void RunScheduledTasks()
{
//do stuff
} 

 

kick it on DotNetKicks.com       [dzone]


Tags:

ASP.NET

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.7
Theme by Mads Kristensen


About Me

I live and work in Salt Lake City, Utah. My background is in aviation. I have a degree in Aeronautical Science from Embry-Riddle Aeronautical University in Prescott, AZ. I have worked as a commercial airline pilot and most recently as a technical advisor for a charter airline.