SPJobDefinition is an object from Microsoft.SharePoint.Administration namespace. By creating Your own class deriving from it, You can simply schedule any task by writting few(maybe a little more :)) lines of code. In derived class You have to create two constructors: one without parameters which will call default base constructor and one which defines parameters like task name, web application and so on.

Next, and the most important thing, is to override Execute() method. This method is called each time when the job is fired, so it should contain all the logic to accomplish what You expect from the job. There is also way to pass some informations to job while creating it’s definition. Simple use job’s Properties attribute(it’s a Hashtable) to add some objects for further use, but watch out – pass only value types, collections or and easy to serialize/deserialize objects. Don’t try to pass complicated objects like SPWeb, because You’ll get an error which can be hard to repair(I’ll talk about it in my next blog entry).

Below is a code sample how to create a job definition and add it to web application.

Creating class deriving from SPJobDefinition

public class myJob : SPJobDefinition

{

public myJob()

: base(){}

public myJob(string jobName, SPWebApplication webApplication)

: base(jobName, webApplication, SPServer.Local, SPJobLockType.Job)

{

this.Title = jobName;

}

public override void Execute(Guid targetInstanceId)

{

try

{

string logName = "Application";

EventLog el = null;

el = new EventLog(logName);

el.Source = this.Name;

string siteUrl = this.Properties["site"] + "";

el.WriteEntry("Job from " + siteUrl + " is working!", EventLogEntryType.Information);

}
catch { }

}

}

Add job to the job definitions

//Deleting existing job
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)

{

if (job.Name == "zavazJob")

{

job.Delete();

}

}

//----------------------

myJob jjob = new myJob("zavazJob", site.WebApplication);

SPDailySchedule schedule = new SPDailySchedule();

schedule.BeginHour = dtcJobTime.SelectedDate.Hour;

schedule.BeginMinute = dtcJobTime.SelectedDate.Minute;

schedule.EndHour = dtcJobTime.SelectedDate.Hour + 1;

schedule.EndMinute = dtcJobTime.SelectedDate.Minute;

jjob.Title = "zavazJob";

jjob.Schedule = schedule;

jjob.Properties.Add("site", site.Url);

jjob.Update();