Creating custom SharePoint 2010 Service Jobs

As in MOSS, SharePoint 2010 has a notion of Service Jobs, running on a defined schedule.

Usually you’d use service job to create scheduled tasks within your portal such as batch business rules validation or alerts processing or really just about anything.

When you create your own Service Job it will be added to this list: http://[central admin url]/_admin/ServiceJobDefinitions.aspx

All Service Jobs have to be provisioned under web application. The best approach is to use SharePoint 2010 feature scoped to a Web Application and create an event receiver for the feature that will create an instance of a job based on the definition.

Here is how you’d go about creating a service job:

1. In your SharePoint solution create a new feature and scope it to the web application.

2. In the Template tree create a new folder where you will define any helpers that will be used to define your Service Job.

3. Create new feature receiver in the feature created in istep 1 and populate the following code in feature activated

SPWebApplication webApplication = (SPWebApplication)properties.Feature.Parent;
// remove any existing job definitions

foreach (SPJobDefinition jobDefinition in jobs)
            {
                if (jobDefinition.Name.StartsWith(“My Service Job Name“, StringComparison.InvariantCultureIgnoreCase))
                {
                    jobDefinition.Delete();
                }
            } 

            try
            {
                MyJobDefinition myJobDefinition = new MyJobDefinition(“”MyServiceJobId“”, webApplication);

            SPMinuteSchedule minuteSchedule = new SPMinuteSchedule();
            minuteSchedule.BeginSecond = 1;
            minuteSchedule.EndSecond = 59;
            minuteSchedule.Interval = 1000;
            myJobDefinition.Schedule = minuteSchedule;
            myJobDefinition.Update();
            }
            catch (Exception ex)
            {
                Microsoft.Office.Server.Diagnostics.PortalLog.DebugLogString(
                    Microsoft.Office.Server.Diagnostics.PortalLogLevel.Unexpected,
                    “Exception in Feature Activated occurred: {0} || {1}”,
                    ex.Message, ex.StackTrace);
                throw;
            }

4. Your feature deactivating method will have Service Job cleanup that will look something like this:

SPWebApplication webApplication = (SPWebApplication)properties.Feature.Parent;
// remove any existing job definitions

foreach (SPJobDefinition jobDefinition in jobs)
            {
                if (jobDefinition.Name.StartsWith(“My Service Job Name“, StringComparison.InvariantCultureIgnoreCase))
                {
                    jobDefinition.Delete();
                }
            } 

5.  Now you noticed we have MyJobDefinition  class from which we create a new job. This class will define what your job is actually doing. It has one method called Execute that will execute the job, you can either call another class that performs your operations if those are complex or you can define operations right in the Execute, here is how something like this will look like:

public class MyJobDefinition : SPJobDefinition
    {
        #region Constructors
        /// <summary>
        /// Default constructor is needed.
        /// </summary>
        public MyJobDefinition()
            : base()
        {
        }
        /// <param name=”jobName”></param>
        /// <param name=”webApplication”></param>
        public MyJobDefinition(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.Job)
        {
            this.Title = “My Service Job Name“; //this will appear in Service Jobs list inside central admin
        }
        #endregion

        #region Methods

        /// <param name=”targetInstanceId”>ID of the content db that is processed by this job.</param>
        public override void Execute(Guid targetInstanceId)
        {
            try
            {

                SPWebApplication webApplication = this.Parent as SPWebApplication;
                // TODO: your scheduled code is here
            }
            catch (Exception ex)
            {
                Microsoft.Office.Server.Diagnostics.PortalLog.DebugLogString(
                    Microsoft.Office.Server.Diagnostics.PortalLogLevel.Unexpected,
                    “Exception in MyJobDefinition occurred: {0} || {1}”,
                    ex.Message, ex.StackTrace);
                throw;
            }
        }
        #endregion
    }

That’s it. Now this is basic implementation and you can improve various parts of your job such as pulling the schedule from configuration file rather than hardcoding it in the code etc. Good luck with your scheduled tasks!

This entry was posted in sharepoint, sharepoint 2010 and tagged , , , . Bookmark the permalink.

Comments are closed.