Create A Timer Job In Sharepoint Programmatically Using Server-Side Object Model

Introduction

In this article, I will explain how to create a Timer Job in SharePoint 2013 programmatically using the Server-Side Object Model. A timer job runs in a specific Windows Service for SharePoint 2013. Timer jobs perform infrastructure tasks for the Timer service. Timer jobs also perform tasks for Web Applications, such as sending Email alerts. A timer job contains a definition of the Service to run and specifies how frequently the Service is started.

Pre-Requisites

  1. Open Visual Studio.
  2. Open the New Project dialog box, expand the Office/SharePoint node, and choose SharePoint Solutions.
    SharePoint node
  3. Choose SharePoint 2013 – Empty Project template. Name the project TimerProject and click the OK button.
    Empty
  4. Choose the Deploy as a farm solution option button and then choose the Finish button to accept the default local SharePoint site.
    Solution exlporer
  5. In Solution Explorer, choose the TimerProject project we created.
    TimerProject

Create Timer Job

  1. Right-click on the Project and select New Folder.
    New Folder
  2. Name the folder as TimerJob.
    TimerJob
  3. Add a class file inside the TimerJob folder.
    Add
  4. The coding for the class file is given below.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace TimerProject.TimerJob
    {
        class TimerClass
        {
        }
    }
    
    Timerclass
  5. Inherit the SPJobDefinition class, make the class public, and create the constructors.
    using Microsoft.SharePoint.Administration;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace TimerProject.TimerJob
    {
        class TimerClass : SPJobDefinition
        {
            public TimerClass() : base() { }
    
            public TimerClass(string jobName, SPService service, SPServer server, SPJobLockType targetType)
                : base(jobName, service, server, targetType) { }
            public TimerClass(string jobName, SPWebApplication webApplication)
                : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
            {
                this.Title = jobName;
            }
            public override void Execute(Guid contentDbId)
            {
                try
                {
                    // Implementation code here
                }
                catch (Exception ex)
                {
                    // Handle exceptions here
                }
            }
        }
    }
    
  6. Next, we need to create a Feature and a FeatureReceiver.
  7. Add a feature by right-clicking on the Features folder.
    Features folder
  8. Name the feature. Make the scope of the Feature as WebApplication.
     WebApplication
  9. Add the event receiver to the Feature by right-clicking on the feature name.
    Add the event
  10. Add the code given below inside the FeatureActivated Event.
    // Uncomment the method below to handle the event raised after a feature has been activated.
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        try
        {
            SPSite site = properties.Feature.Parent as SPSite;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite elevatedSite = new SPSite(site.ID))
                {
                    // make sure the job isn't already registered
                    foreach (SPJobDefinition job in elevatedSite.WebApplication.JobDefinitions)
                    {
                        if (job.Name == "TestTimerJob")
                        {
                            job.Delete();
                            break;
                        }
                    }
                    // install the job
                    TimerClass corpProfileJob = new TimerClass("TestTimerJob", site.WebApplication);
                    // Updates the timer schedule values
                    SPDailySchedule schedule = new SPDailySchedule();
                    schedule.BeginHour = 4;
                    schedule.EndHour = 5;
                    schedule.BeginMinute = 30;
                    schedule.EndMinute = 0;
                    schedule.BeginSecond = 0;
                    schedule.EndSecond = 0;
                    corpProfileJob.Schedule = schedule;
                    elevatedSite.WebApplication.JobDefinitions.Add(corpProfileJob);
                }
            });
        }
        catch (Exception ex) { }
    }
    
  11. Add the code, given below, inside FeatureDeactivated Event.
    // Uncomment the method below to handle the event raised before a feature is deactivated.
    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    {
        try
        {
            SPSite site = properties.Feature.Parent as SPSite;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite elevatedSite = new SPSite(site.ID))
                {
                    // delete the job
                    foreach (SPJobDefinition lockjob in elevatedSite.WebApplication.JobDefinitions)
                    {
                        if (lockjob.Name == "TestTimerJob")
                        {
                            lockjob.Delete();
                        }
                    }
                }
            });
        }
        catch (Exception ex) { }
    }
    
  12. Make the Activation on Default of the feature as false and always make Force Install as true in Feature properties.
    Force Install
  13. Deploy our solution into the SharePoint portal.
    SharePoint portal
  14. After completing deployment, activate the feature in Web Application.
    Deployment
  15. See the timer job, which gets listed on the Monitoring->Review Job Definitions in Central Administration.
    Review
  16. To debug the timer job, we need to attach it with the process OWSTIMER.EXE to debug the timer job. The execution Execute method will be the first method that gets invoked.
    Debug

Summary

Thus, you have learned how to Create a Timer Job in SharePoint 2013 programmatically using the Server-Side Object Model.