Saturday, August 30, 2008

How to create Scheduled Jobs in .net web applications.

How to create Scheduled Jobs in .net web applications.

Calling a function at predefined iteration of time has been one of the key requirements of web applications.
Example:
You want to automatically archive the data.
You want to automatically purge the data.
You want to automatically send the News Letters.
You want to take backup of the files or database etc.

Generally this type of functionality can be easily archived by creating and configuring scheduled jobs in SQL Server.

What if you are using the express edition of SQL Server?
You cannot take advantage of this feature because all the editions of SQL Server do not provide this functionality.

In this article I will explain how we can achieve this functionality using purely .Net framework class.

First of all let’s thanks System.Threading class. The main cream lies inside this class shipped in .Net Framework. Many of us usually do not use it but believe me its one of the most beautiful classes of the framework.

Anyways

Following are the steps which you need to perform:

Step 1) Create a class called Jobs.cs

[sourcecode language='csharp']

namespace myScheduler
{
    public sealed class Jobs
    {
        public Jobs(){}

        public static void DailyJob(object state)
        {
           //Your dream goes here.
        }

        public static void HourlyJob(object state)
        {
            //Your dream goes here.
        }
    }
}

[/sourcecode]

Jobs class includes the below two functions that will be called by our scheduler which we will create in the second step.
I have created two functions for this purpose.
DailyJob: Will be called daily by the scheduler.
HourlyJob: Will be called hourly by the scheduler.

 

Step 2) Create a class called Scheduler.cs

[sourcecode language='csharp']

using System;
using System.Threading;

namespace myScheduler
{
    public sealed class Scheduler
    {
        public Scheduler() { }

        public void Scheduler_Start()
        {
            TimerCallback callbackDaily = new TimerCallback(Jobs.DailyJob);
            Timer dailyTimer = new Timer(callbackDaily, null, TimeSpan.Zero, TimeSpan.FromHours(24.0));

            TimerCallback callbackHourly = new TimerCallback(Jobs.HourlyJob);
            Timer hourlyTimer = new Timer(callbackHourly, null, TimeSpan.Zero, TimeSpan.FromHours(1.0));
        }
    }
}

[/sourcecode]

Scheduler class contains the actual mechanism for running jobs created in Jobs class in Step one.

Timer: Mechanism for executing method at specified time intervals. This method has 5 overloads which we can use as per our needs. Some of its parameters are
TimerCallback: Represents the method that you want to actually callback on at a particular interval of time.
State: Any type of object you want to pass to your callback method.
Due Time: Amount of delay after which callback will be invoked. TimeSpan.Zero means immediately.
Period: Time period between invocations of callback function.

 

Step 3) Add Global.asax file to your web project. In Application_Start event instantiate Scheduler object and make a call to Scheduler_Start() method.

[sourcecode language='html']

<%@ Application Language="C#" %>
<%@ Import Namespace="myScheduler" %>



[/sourcecode]

 

You are done.

How it works?
Whenever the applications is first started the  Application_Start() in Global.asax is called and this calls Scheduler_Start() method which configures all the Jobs that we have created.

I have demonstrated a daily and hourly job in the above examples. In order to debug and test this code you need to wait for an Hour or a Day. Don’t panic I have done this intentionally. So in order to brush up your above learning’s prepare a job in Jobs.cs file that would be called every minute. Configure the callback and timer for your new job in Scheduler.cs file and enjoy the gist of scheduling.

Note: After running the project once do not forget to restart the IIS because Application_Start() wont be called every time you run your project. You know why?

4 comments:

Hemang said...

Hi Dhaval,
Great article, i was searching for the same kind and found it.
I am pending to test this code but i am sure it will work.

Abed said...

your article is very good & i need to this code in job

Mayur Mewada said...

Hi Dhaval

I tried and it works fine. Great job dude.

Nice article...

geebeex said...

http://code.google.com/p/ncron/