Monday, April 12, 2010

How to Create a Custom Timer Jobs in Windows SharePoint Services 3.0?

What is Timer Job in MOSS?

             We create custom jobs that are executed at set intervals. These jobs, known as timer jobs, are similar to those tasks that you can create in any version of Windows by using the Task Scheduler application.

             This capability is useful for scheduled process jobs because you keep everything in Windows SharePoint Services rather than create a console .exe

Advantage: 
             The timer service knows the topology of the Office SharePoint Server farm, and that you can load balance the jobs across all the servers in the farm.


How To Create a Timer Job?

1. Open the VS 2008  Select File->Project->New Project.

2. Select the Project type WSP Builder -> WSP Builder Project.(WSP builder is mainly used to create .WSP file).

3. Enter the Project Name and Click OK.



4. Add a new class file that inherits from SPJobDefinition.
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace TaskTimerJob
{
public class TaskTimerJobImplementation :SPJobDefinition
{
// Other implementation.......
}
}

5. Then we need to overrides the Execute method. This is the method that is called when the job is executed by Windows SharePoint Services.

public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);

            // get a reference to the current site collection's content  database
            SPWebApplication oWebApp = this.Parent as SPWebApplication;
            SPContentDatabase oConDB =  oWebApp.ContentDatabases[targetInstanceId];

            // get a reference to the "Tasks" list in the RootWeb of the  first site collection in the content database
            SPList taskList = oConDB.Sites[0].RootWeb.Lists["Testing"];

            // create a new task
            SPListItem newTask = taskList.Items.Add();
            newTask["Title"] = "Auto Task : " +  DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss");
            newTask.Update();

        }


Complete Source : TaskTimerJobImplementation.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace TaskTimerJob
{
    public class TaskTimerJobImplementation :SPJobDefinition
    {
        public TaskTimerJobImplementation()
            : base()
        {

        }

        public TaskTimerJobImplementation(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {

        }

        public TaskTimerJobImplementation(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Task Creator"; 
        }

        public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);

            // get a reference to the current site collection's content database
            SPWebApplication oWebApp = this.Parent as SPWebApplication;
            SPContentDatabase oConDB = oWebApp.ContentDatabases[targetInstanceId];

            // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database
            SPList taskList = oConDB.Sites[0].RootWeb.Lists["Testing"];

            // create a new task
            SPListItem newTask = taskList.Items.Add();
            newTask["Title"] = "Auto Task : " + DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss");
            newTask.Update();

        }
    }
}

How to Deploy this Timer Job?

1. Now we need to create installable Feature .

2. Right - Click the Project -> Add -> New Item.



3. Select the WSPBuilded - > Features with Receiver in Add new Item Dialog box.


4. Enter the Feature Name in Name Box, Click Add button.

5. Set the Feature settings in Feature Setting Dialog box.


6. Set the property and click OK.


7. Add the Job Activation code in FeatureActived Method.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            String TaskName = "Task Creator";

            // make sure the job isn't already registered
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == TaskName)
                    job.Delete();
            }

            // install the job
            TaskTimerJobImplementation oCreateTaskTimerJob = new TaskTimerJobImplementation(TaskName, site.WebApplication);

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 5;

            oCreateTaskTimerJob.Schedule = schedule;

            oCreateTaskTimerJob.Update();
        }


Complete Code Snippet :  TaskTimerJob.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace TaskTimerJob
{
    class TaskTimerJob : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            String TaskName = "Task Creator";

            // make sure the job isn't already registered
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == TaskName)
                    job.Delete();
            }

            // install the job
            TaskTimerJobImplementation oCreateTaskTimerJob = new TaskTimerJobImplementation(TaskName, site.WebApplication);

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 5;

            oCreateTaskTimerJob.Schedule = schedule;

            oCreateTaskTimerJob.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            String TaskName = "Task Creator";

            // make sure the job isn't already registered
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == TaskName)
                    job.Delete();
            }
        }
    }
}

8. Build the Project as .WSP , Right click Project Select WSP Builder -> Build WSP.


9. After success full Completion, we can find *.WSP file in Project.


How to install the feature and activate?

1. Add this solution by using "Addsolution" command.


2. Now we need to deploy the solution . Open the Central Administration -> Operations -> Solution Management.






3. Activate this feature in a target site.

 Open the target site , Site Actions -> Site settings - >Site collection Feature.


4. After success full activation we can see the result in a target List.



I hope you can enjoy this article.


Thank You.

1 comment:

David said...

That is just awsome !!! Very nice and complete.