Latest Posts

How to create SharePoint Timer Job programmatically

Timer job is the program that executes/runs based on the schedule in background. In this tutorial, we will see how to use SharePoint 2013 on-premises to create a Timer Job. Even though in the age of SharePoint Online it’s a bit old to talk about on-premise Timer Job but let’s still go in-depth of the same.

Step-by-step process to create SharePoint Timer Job

  1. Open Visual Studio
  2. Crete SharePoint 2013 Empty Project
  3. Crete SharePoint 2013 Empty Project
  4. Select Deploy as a Farm Solution
  5. Timer Job as a Farm Solution
  6. Right Click on Project and add a class to it. Keep the Name as TimerJob.cs
  7. Add Timer Job class file
  8. Below is the code for newly created TimerJob.cs file. You can copy the code in your application.
    • using System;
    • using System.Collections.Generic;
    • using System.Linq;
    • using System.Text;
    • using System.Threading.Tasks;
    • using Microsoft.SharePoint.Administration;
    • namespace TimerJob
    • {
    •     class TimerJob : SPJobDefinition
    •     {
    •         public TimerJob() : base()
    •         {
    •         }
    •         public TimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType) : base(jobName, service, server, targetType)
    •         {
    •             this.Title = "TimerJob";
    •         }
    •         public TimerJob(string jobName, SPWebApplication webApplication) : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
    •         {
    • this.Title = "TimerJob";
    •         }
    •         public override void Execute(Guid ContentDatabaseID)
    •         {
    •             try
    •             {
    •               // Write your program here. This will be executed whenever TimerJob runs
    •             }
    •             catch (Exception ex)
    •             {}
    •         }
    •     }
    • }

    Note: In this Timer Job class, there’s one method called Execute. This is the method where we put our logic to execute when Timer Job runs.

    Specify Timer Job Lock Type

    Member Name

    Description

    SPJobLockType.None

    There’s no lock provided. Timer Job will run on each machine of the farm where parent service is configured

    SPJobLockType.ContentDatabase

    Locks the Content Database. Timer Job runs once for each content database associated with web application

    SPJobLockType.Job

    It runs only on one machine in Farm

  9. Now, add a new feature to the project
  10. Right-click on Feature folder and add a feature
  11. Give Title of the Feature and keep the scope as WebApplication
  12. Timer Job Feature definition
  13. Now, add an Event Receiver. Right Click on Newly added feature and click on Add Event Receiver.
  14. We will add code for Feature Activated and Feature Deactivated events
  15. Timer Job Feature Activation Code below:

    • public override voidFeatureActivated(SPFeatureReceiverProperties properties)
    • {
    •             try
    •             {
    •                 SPSecurity.RunWithElevatedPrivileges(delegate ()
    •                 {
    •                     SPWebApplication oWebApplication = (SPWebApplication)properties.Feature.Parent;
    •                     foreach (SPJobDefinition jobDefinition in oWebApplication.JobDefinitions)
    •                     {
    •                         // If a Job with the same name already exists, delete it.
    •                         if (jobDefinition.Name == "TimerJob")
    •                         {
    •                             jobDefinition.Delete();
    •                             break;
    •                         }
    •                     }
    •                     // install the job  
    •                     TimerJob timerJobObject = new TimerJob("TimerJob", oWebApplication);
    •  
    •                     // Updates the timer schedule values  
    •                     SPDailySchedule Timerschedule = new SPDailySchedule();
    •                     Timerschedule.BeginHour = 4;
    •                     Timerschedule.EndHour = 5;
    •                     Timerschedule.BeginMinute = 30;
    •                     Timerschedule.EndMinute = 0;
    •                     Timerschedule.BeginSecond = 0;
    •                     Timerschedule.EndSecond = 0;
    •                     timerJobObject.Schedule = Timerschedule;
    •                     oWebApplication.JobDefinitions.Add(timerJobObject);
    •                 });
    •             }
    •             catch (Exception ex) { }
    • }

    Timer Job Feature Deactivation Code below:

    • public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    • public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    •         {
    •             try
    •             {
    •                 SPSecurity.RunWithElevatedPrivileges(delegate ()
    •                 {
    •                     SPWebApplication oWebApplication = (SPWebApplication)properties.Feature.Parent;
    •                     // On deactivating the feature, delete the Timer Job  
    •                     foreach (SPJobDefinition jobDefinition in oWebApplication.JobDefinitions)
    •                     {
    •                         if (jobDefinition.Name == "TimerJob")
    •                         {
    •                             jobDefinition.Delete();
    •                         }
    •                     }
    •                 });
    •             }
    •             catch (Exception ex) { }
    • }
  16. In the feature activation code above, we have created an object SPDailySchedule, which is used for setting timer job to run once Every Day. The same way we can also create other schedules as mentioned below.
  17. Schedule Class

    Description

    SPYearlySchedule

    Timer Job runs every Year

    SPMonthlySchedule

    Timer Job runs every Month

    SPMonthlyByDaySchedule

    Timer Job Runs on the given day and week of the month. i.e. 2nd Sunday of the month

    SPWeeklySchedule

    Timer Job runs once per week

    SPDailySchdedule

    Timer Job runs once per day

    SPHourlySchedule

    Timer Job runs once every hour

    SPMinuteSchedule

    Timer Job runs after every minute-interval specified.

    SPOneTimeSchedule

    Timer Job runs only one time

  18. By default, you can keep the feature deactivated. Open the feature >> Click on properties >> as shown in below Screenshot, keep the value as False for the property Activate on Default.
  19. Timer Job Feature activation
  20. Now, you can deploy the solution from the visual studio. Right-click on Solution and click on Deploy.
  21. Timer Job Feature deploy
    Note:

    Whenever you deploy Timer Job solution, make sure you restart timer service from services.msc. You can follow the below-mentioned steps.

    Restart SharePoint Timer Service :

    • Go to search bar and look for services.msc >> click on it.
    • windows search services
    • Locate SharePoint Timer Service >> Right-click on it and Restart it
    • windows SharePoint Timer Service

    Activate the Feature

    • Go to Central Administration >> Manage Web Applications. Click on the Web Application and then click on the Manage Features from Ribbon.
    • Locate Manage Feature in Central administration
    • You will be able to see the feature you just deployed. Activate the feature.
    • activate timer job feature

    Locate the deployed Timer Job

    • Go to Central Administration >> Monitoring >> Review Job Definition
    • review timer job definition
    • Find out the Job you deployed and click on it. You can see the schedule already set, whatever you had set programmatically.
    • timer job schedule

    Timer Job Debugging

    • Debug Feature Receivers: If you want to debug feature Activation / Deactivation methods, you need to press Ctrl + Alt + P and Attach w3wp.exe process.
    • debug feature receiver
    • Debug Timer Job: To debug the actual implementation of the Timer Job, you need to put a breakpoint in Execute() Method in Timer Job Class (TimerJob.cs in above example), press Ctrl + Alt + p and attach OWSTIMER.EXE process.
    • Debug Timer Job

Conclusion:

We went through the process of creating and deploying timer job in SharePoint on-premises environment. We also understand how we can debug the SharePoint Timer Job.


We value your Feedback:

Page URL:

Name:

 

Email:

 
 

Suggestion:

 

© 2024 Code SharePoint