Wednesday, April 7, 2010

Creating and deploying custom SharePoint Timer jobs


Step 1: Create a class with inherits from SPJobDefinition
public class NotificationsTimer : SPJobDefinition
{
public NotificationsTimer(): base(){}

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

public NotificationsTimer(string jobName, SPWebApplication webApplication)
: base(jobName, webApplication, null, SPJobLockType.ContentDatabase){
this.Title = "Notifications timer"; 
}

public override void Execute(Guid targetInstanceId){
SPWebApplication webApplication = this.Parent as
SPWebApplication;

SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];

SPList _testList = contentDb.Sites[0].RootWeb.Lists["test list"];

SPListItem item = _testList.Items.Add();
item["Title"] = "test from timer job1";

item.Update();}
} 



Step 2: Create Feature.xml including this assembly as under.

<xml version="1.0" encoding="utf-8">
<Feature Id="3b0947a0-c5b6-4b12-a1a0-3f86d14b9816" Title="NotificationsTimer" Description="Description for NotificationsTimer" Version="12.0.0.0" Hidden="FALSE" Scope="Site" 
DefaultResourceFile="core" ReceiverAssembly="SP.WSPBuilder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c6cba5eb84968b9b" 
ReceiverClass="WSPBuilder.NotificationsTimer" xmlns="http://schemas.microsoft.com/sharepoint/"> <ElementManifests>
<ElementManifest Location="elements.xml"/>
</ElementManifests>
</Feature>



Step 3: While the feature is being activated, setup the schedule and add to the job instance as under.


SPSite _site = properties.Feature.Parent as SPSite;

//Make sure job is not already registered
foreach (SPJobDefinition job in _site.WebApplication.JobDefinitions)
{
if (job.Name == JOB_NAME)
job.Delete();
}

//Install the job
TimerJobs.NotificationsTimer _job = new TimerJobs.NotificationsTimer(JOB_NAME, _site.WebApplication);

SPMinuteSchedule _schedule = new
SPMinuteSchedule();

_schedule.BeginSecond = 0;
_schedule.EndSecond = 59;
_schedule.Interval = 5;
_job.Schedule = _schedule;
_job.Update();


Timer job should be up and running after the feature is activated. To view the existing deployed timer jobs, use Central Administration.

Technorati Tags: ,,,

1 comment:

  1. SPWebApplication webApplication = this.Parent as
    SPWebApplication;

    "SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];"

    SPList _testList = contentDb.Sites[0].RootWeb.Lists["test list"];

    In execute method, contentDb is null in this case. Do v have any other way to access SPList by using "targetinstanceID" of execute method?.

    ReplyDelete