Quantcast
Channel: Visual SharePoint
Viewing all articles
Browse latest Browse all 10

Timer Job with SPJobDefinition

$
0
0

SharePoint allows you to write, install and schedule Timer Jobs. A Timer Job has a job definition (that must be defined and implemented in a class derived from SPJobDefinition), an automatic entry as SPRunningJob if it is executing, other eventual entries in SPJobHistory for past executions (see the collection returned by SPJobDefinition.HistoryEntries). Scheduling of the Timer Job is usually performed in feature’s event receiver, after the activation of the feature (remark the job must be deleted when the feature is deactivating).

SharePoint Job Model

Jobs can be defined and performed for a web service (throughout the whole farm) or within just one web application. Both SPService and SPWebApplication classes expose member properties such as JobDefinitions (for SPJobDefinifion-based entries), RunningJobs (for SPRunningJob entries), JobHistoryEntries (for SPJobHistory entries). SPJobDefinition has back references to the parent SPService or SPWebApplication.

Here is the big picture with the relationships between web services or applications with defined jobs:

This diagram shows details about the structure of some essential job-related classes, such as SPJobDefinition, SPRunningJob and SPJobHistory:

Simple Timer Job Implementation

Let’s implement now a very simple Timer Job at the SPWebApplication level. We’ll call it “MyJobDefinition“. The actual implementation of the job is done in a class derived from SPJobDefinition. We need a JobName, constructors for serialization (SPJobDefinition is a SPPersistedObject) and the actual execution, in the Execute(…) override method. Our Timer Job will simply add a new item in the Tasks list:

public class MyJobDefinition : SPJobDefinition {

    public const string JobName = "MyJobDefinition";

    public MyJobDefinition() : base() { }
    public MyJobDefinition(SPWebApplication webApp) : base(JobName, webApp, null, SPJobLockType.Job)
    { Title = "My Job Definition"; }

    public override void Execute(Guid targetInstanceId) {
        SPWebApplication webApp = this.Parent as SPWebApplication;
        SPList taskList = webApp.Sites[0].RootWeb.Lists["Tasks"];
        SPListItem newTask = taskList.Items.Add();
        newTask["Title"] = DateTime.Now.ToString();
        newTask.Update();
    }
}

The job needs installation and configuration through a SharePoint feature. We simply add this feature, with a related event receiver (a custom class derived from the abstract SPFeatureReceiver). When deactivating, the feature must remove any job with the same JobName eventually installed. When activated, the feature reinstalls, schedules and starts the timer job:

[Guid("7392ad9a-7ee0-42a9-b4f2-fdb9b620b746")]
public class MyJobDefinitionEventReceiver : SPFeatureReceiver {

    public override void FeatureActivated(SPFeatureReceiverProperties properties) {
        DeleteJob(properties);

        // create schedule
        SPMinuteSchedule schedule = new SPMinuteSchedule();
        schedule.BeginSecond = 0;
        schedule.EndSecond = 59;
        schedule.Interval = 1;

        // add job
        MyJobDefinition simpleJob = new MyJobDefinition(properties.Feature.Parent as SPWebApplication);
        simpleJob.Schedule = schedule;
        simpleJob.Update();
    }

    public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {
        DeleteJob(properties);
    }

    private void DeleteJob(SPFeatureReceiverProperties properties) {
        SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
        foreach (SPJobDefinition job in webApp.JobDefinitions)
            if (job.Name.Equals(MyJobDefinition.JobName, StringComparison.OrdinalIgnoreCase))
                job.Delete();
    }
}

SPJobDefinition can and usually connects with a scheduler, for repetitive tasks. You can use one of the specialized built-in classes derived from the abstract SPSchedule: SPOneTimeSchedule, SPMonthByDaySchedule, SPDailySchedule, SPMonthlySchedule, SPHourlySchedule or SPMinuteSchedule.


Viewing all articles
Browse latest Browse all 10

Trending Articles