web 2.0

Scheduled ASP.NET Task Manager

Hi,

In this article I’ll talk about Scheduled Task Manager in a ASP.NET Environment. We often need to make scheduled tasks running in background but it’s not very simple to make it with ASP.NET.

I based my article on the StackOverFlow article which uses ASP.NET Cache to schedule tasks.

First of all here is the IScheduledTask Interface in order to Implements our Custom Tasks

public interface IScheduledTask
{
    TimeSpan Expiration { get; set; }
    Boolean IsOnce { get; set; }
    String Name { get; set; }
    void Run();
}

Now the ScheduledTaskManager

public class ScheduledTaskManager
{
    #region Singleton

    static readonly ScheduledTaskManager instance = new ScheduledTaskManager();

    static ScheduledTaskManager()
    {
    }

    ScheduledTaskManager()
    {
    }

    public static ScheduledTaskManager Instance
    {
        get
        {
            return instance;
        }
    }

    #endregion

    #region Private Fields

    private static CacheItemRemovedCallback OnCacheRemove = null;

    #endregion

    #region Public Methods

    public void AddTask(IScheduledTask task)
    {
        OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);

        HttpRuntime.Cache.Insert(task.Name, task, null,
        DateTime.Now.Add(task.Expiration), Cache.NoSlidingExpiration,
        CacheItemPriority.NotRemovable, OnCacheRemove);
    }

    #endregion

    #region Private Methods

    private void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
    {
        var task = v as IScheduledTask;
        if (task == null) return;

        task.Run();
        if (!task.IsOnce)
            AddTask((IScheduledTask)v);
    }

    #endregion
}

We can now implement our Custom Task

public class MyTask : IScheduledTask
{
    #region IScheduledTask Members

    public TimeSpan Expiration
    {
        get; set;
    }

    public string Name
    {
        get; set;
    }

    public void Run()
    {
        Debug.WriteLine("Running !");
    }

    public bool IsOnce
    {
        get; set;
    }

    #endregion
}

Sample Usage :

public class Global : System.Web.HttpApplication
{

    protected void Application_Start(object sender, EventArgs e)
    {
        var task = new MyTask {Name = "MyTask", Expiration = new TimeSpan(0, 0, 10)};
        ScheduledTaskManager.Instance.AddTask(task);

        var task2 = new MyTask { Name = "MyTask2", Expiration = new TimeSpan(0, 0, 5) };
        ScheduledTaskManager.Instance.AddTask(task2);
    }
}

 

Simple :)

Hope this help’s !



Views(3126)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

ASP.NET | C#

Comments

Add comment


 

biuquote
Loading



Technorati Profile