Wednesday, November 12, 2014

SharePoint 2013 - Creating Custom Timer Jobs

In the previous post, we had an overview of SharePoint 2013 timer jobs and we discussed about the service, processes and monitoring of timer jobs. Apart from in-built timer jobs, custom timer jobs can be created for various background tasks. Let's take a look at the major steps and components for creating, deploying and managing a custom timer job.

Create the Timer Job Class
Following are the steps for creating the Timer job class.
1) Create a new empty SharePoint project in visual studio and add a new class that inherits from SPJobDefinition class which comes under Microsoft.SharePoint.Administration namespace.

2) Implement the base constructor provide by SPJobDefinition class as follows. You can either target the timer job to SPWebApplication or SPService. In our demo we will target to SPWebApplication.

Note: In the above code, SPJobLockType class enables locking on the Timer job. Following are the different types of Locks.
i) None: Locking is disabled. Job runs on all servers in the farm unless you pass an SPServer object for the server parameter.
ii) ContentDatabase: Job runs for each content database that is associated with the job's web application.
ii) Job: Only one server can run the job at a time.

3) Write the code for timer job functionality in the Execute(Guid targetInstanceId) method. In our demo, we will write the code to log the time stamps in a custom list named TimeStamps. which has been created in the root site collection.

Note: In the above code, Execute method has a Guid as parameter. For target types of SPContentDatabase this is the database ID of the content database being processed by the running job. For all other target types, this value is Guid.Empty.

Following is the complete code for the Timer Job class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace TimerJobsDemo
{
    public class SpTechBytesTimer : SPJobDefinition
    {
        public SpTechBytesTimer() : base() { }

        public SpTechBytesTimer(string jobName, SPWebApplication webapp) :
            base(jobName, webapp, null, SPJobLockType.None){ }

        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication objSPWebApplication = this.Parent as SPWebApplication;
            SPList objSPList = objSPWebApplication.Sites[0].RootWeb.Lists["TimeStamps"];
            SPListItem objNewTask = objSPList.Items.Add();
            objNewTask["Title"] = "TimeStamp: " + DateTime.Now.ToString();
            objNewTask.Update();
        }
    }
}

Deploy Timer Job
Following are the steps for deploying the Timer job.
1) Create a new Feature scoped to WebApplication.

Note: The Scope of the feature should be either WebApplication or Farm since SharePoint 2013 security does not allow a Site or Web scoped feature to make any changes in the WebApplication even with elevated privileges and will throw an "Access Denied" Exception

2) Add a Feature Receiver and set the target entity such as SPService or SPWebApplication in the FeatureActivated event as follows. The following code configures the timer job to run for a time span from 0-59 (1 minute) with an interval of 3. This means the timer job will run after every 3 minutes.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWebApplication objSPWebApp = properties.Feature.Parent as SPWebApplication;
SpTechBytesTimer objImageUpdator = new SpTechBytesTimer("SpTechBytes Timer", objSPWebApp);
SPMinuteSchedule objSchedule = new SPMinuteSchedule();
objSchedule.BeginSecond = 0;
objSchedule.EndSecond = 59;
objSchedule.Interval = 3;
objImageUpdator.Schedule = objSchedule;
objImageUpdator.Update();
}

Note: In the above code, the time interval is defined by setting the Schedule property to an instance of one of the following SPSchedule class types:
i) SPMinuteSchedule: This class can be used to schedule jobs for periods of time in terms of minutes or seconds.
ii) SPHourlySchedule: Runs the job every hour.
iii) SPDailySchedule: Runs the job daily.
iv) SPWeeklySchedule: Runs the job weekly.
v) SPMonthlySchedule: Runs the job monthly.
vi) SPYearlySchedule: Runs the job yearly.

3) The Timer Job can be removed from Job Definitions by deleting it from the SPJobDefinition Collection of the WebApplication in the FeatureDeactivating event as follows:
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWebApplication objSPWebApp = properties.Feature.Parent as SPWebApplication;
SPSecurity.RunWithElevatedPrivileges(delegate
{
    foreach (SPJobDefinition Job in objSPWebApp.JobDefinitions)
    {
        if (Job.Name.Equals("SpTechBytes Timer"StringComparison.OrdinalIgnoreCase))
        {
Job.Delete();
        }
    }
});
}


4) Build and deploy the solution.

Manage Timer Job
1) Go to the target WebApplication and activate the Feature for Timer Job.

2) Go to Central Admin-> Monitoring-> Review Job Definitions. You will see that newly created Timer Job is available in the Job definitions list.

3) Click on the timer job to view its details and verify whether the configurations are as per your code. For starting the timer job manually you can click on the Run Now button.
4) Go the root site collection and open the TimeStamps list. You will notice that a time stamp is entered every 3 minutes.

5) For removing the timer job deactivate the feature from the WebApplication, the Timer job will be deleted from the Job Definitions list time stamps will no longer be updated in the TimeStamps list.

Hope this post was helpful!

1 comment:

  1. Thanks for sharing such a great information..Its really nice and informative.
    SharePoint Training

    ReplyDelete

Note: Only a member of this blog may post a comment.