Scenario:
You want to run some code on a regular interval and decided to write a timer Job.
Sample Timer Job Code:
using System;Feature Activation Code:
using System.Net;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace SharePoint.TrainingSamples {
public class SharePointTimerJob:SPJobDefinition {
public SharePointTimerJob():base(){ }
public SharePointTimerJob(string jobName,SPWebApplication webApplication)
:base(jobName, webApplication, null, SPJobLockType.ContentDatabase) {
this.Title = "MyTimerJob";
}
public override void Execute (Guid targetInstanceId) {
foreach (SPSite siteCollection in this.WebApplication.Sites) {
// Code to be executed as a part of Timer Job
foreach (SPSite siteCollection in this.WebApplication.Sites)
{
SPWebApplication webApplication = this.Parent as SPWebApplication;
SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
// get reference to "Tasks" list in the RootWeb of
// the first site collection in the content database
SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];
// create a new task, and update item
SPListItem newTask = taskList.Items.Add();
newTask["Title"] = DateTime.Now.ToString();
newTask.Update();
}
}
}
}
}
Now that timer job is ready you need to add it to SharePoint Timer Jobs Store, One way is to add it as a part of Feature Activation
// get a reference to our job class in the GACFeature De-Activation Code:
public override void FeatureActivating (SPFeatureReceiverProperties properties) {
SPSite site = properties.Feature.Parent as SPSite;
//This is the timer class you have created above
SharePoint.TrainingSamples.SharePointTimerJob oSharePointTimerJob = new SharePoint.TrainingSamples.SharePointTimerJob("MyTimerJob", site.WebApplication);
// set the execution schedule to every 5 minute
SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 5;
oSharePointTimerJob.Schedule = schedule;
//update the job
oSharePointTimerJob.Update();
}
You might want to remove it from SharePoint Timer Jobs Store on de-activation
public override void FeatureDeactivating (SPFeatureReceiverProperties properties) {Articles:
SPSite site = properties.Feature.Parent as SPSite;
// Delete the job.
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) {
if (job.Name == "MyTimerJob")
job.Delete();
}
}
MUST READ : Issues with Timer job , OTHER Helpful links MSDN , Must Read , Andrew Connell
3 comments:
How to execute this code in SharePoint 2010?
Nice post! I notice you can pretty easily reference a list on the root web. Any idea how the code would look if you wanted to reference a list in a subsite?
Brian
You can use
SPWeb web = sitecollectionobject.OpenWeb("/subsite"); ,
this way you get a subsite and then you can do
SPList list = web.List["MyList"];
Post a Comment