How to Create Timer Job in SharePoint 2013

What a SharePoint Timer Job is

A Timer Job is a periodically executed task inside SharePoint Server. It can do various tasks within the SharePoint environment on a scheduled time event basis.

Create Timer Job step-by-step

  1. Open the Visual Studio 2012.
  2. Click New Project.
  3. Select the Empty SharePoint Solution Template.



  4. Select Deploy as Farm Solution.



  5. Add a new class to the project and provide the name (TimerJobDemo.cs).



  6. To do this, right-click on the project name in Solution Explorer, select Add -> New Item. Under the C# category select the Code tab, select Class and provide the class name. TimerJobApplication -> Add -> New Item -> Class.

  7. Derive this TimerJobDemo from the SPJobDefinition class.

  8. You need to add the following statements to do this.
    1. using Microsoft.SharePoint;  
    2. using Microsoft.SharePoint.Administration;  
    3. public class TimerJobDemo:SPJobDefinition  
    4. {  
    5. }  
  9. Add the following three constructors to your class.
    1. public TimerJobDemo():base()  
    2. {   
    3. }  
    4.   
    5. public TimerJobDemo (string jobName, SPService service) base(jobName, service, null, SPJobLockType.None)  
    6. {  
    7.     this.Title = "Demo Timer Job";  
    8. }  
    9.   
    10.   
    11. public TimerJobDemo(string jobName, SPWebApplication webapp) base(jobName, webapp, null, SPJobLockType.ContentDatabase)  
    12. {  
    13.     this.Title = "Demo Timer Job";  
    14. }  
  10. Override the Execute() method to do your stuff. Whenever the timer job executes, it will run the code written inside the Execute() method.
    1. SPWebApplication webApp = this.Parent as SPWebApplication;  
    2. SPList taskList = webApp.Sites[0].RootWeb.Lists["TimerLists"];  
    3. SPListItem newTask = taskList.Items.Add();  
    4. newTask["Title"] = "Job runs at " + DateTime.Now.ToString();  
    5. newTask.Update();  

Register the Timer Job Definition

Use the following the procedure to register the Timer Job Definition:

  1. Add a new feature to register our custom timer job.
  2. Right-click on Features inside the project in the Solution Explorer and click "Add Feature".



  3. Rename this feature to TimerJobFeature.
  4. Select the scope of the Timer job as “WebApplication”.



  5. Open the Feature properties and set “Active On Default” to “False”.



  6. Right-click on the “TimerJobFeature” and select “Add Event Receiver”.



  7. Uncomment the FeatureActivated and FeatureDeactivating methods and write the code as in the following.
    1. const string JobName = "Demo Job";  
    2. public override void FeatureActivated(SPFeatureReceiverProperties properties)  
    3. {  
    4.     try  
    5.     {  
    6.         SPSecurity.RunWithElevatedPrivileges(delegate()  
    7.         {  
    8.             SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;                      
    9.             DeleteExistingJob(JobName, parentWebApp);  
    10.             CreateJob(parentWebApp);  
    11.         });  
    12.     }  
    13.     catch (Exception ex)  
    14.     {  
    15.         throw ex;  
    16.     }  
    17. }  
    18. private bool CreateJob(SPWebApplication site)  
    19. {  
    20.     bool jobCreated = false;  
    21.     try  
    22.     {  
    23.         TimerJobDemo job = new TimerJobDemo(JobName, site);  
    24.         SPMinuteSchedule schedule = new SPMinuteSchedule();  
    25.         schedule.BeginSecond = 0;  
    26.         schedule.EndSecond = 59;  
    27.         schedule.Interval = 15;  
    28.         job.Schedule = schedule;  
    29.   
    30.         job.Update();  
    31.     }  
    32.     catch (Exception)  
    33.     {  
    34.         return jobCreated;  
    35.     }  
    36.     return jobCreated;  
    37. }  
    38. public bool DeleteExistingJob(string jobName, SPWebApplication site)  
    39. {  
    40.     bool jobDeleted = false;  
    41.     try  
    42.     {  
    43.         foreach (SPJobDefinition job in site.JobDefinitions)  
    44.         {  
    45.             if (job.Name == jobName)  
    46.             {  
    47.                 job.Delete();  
    48.                 jobDeleted = true;  
    49.             }  
    50.         }  
    51.     }  
    52.     catch (Exception)  
    53.     {  
    54.         return jobDeleted;  
    55.     }  
    56.     return jobDeleted;  
    57. }  
    58.   
    59. public override void FeatureDeactivating(SPFeatureReceiverProperties properties)  
    60. {  
    61.   
    62.     lock (this)  
    63.     {  
    64.         try  
    65.         {  
    66.             SPSecurity.RunWithElevatedPrivileges(delegate()  
    67.             {  
    68.                 SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;  
    69.                 DeleteExistingJob(JobName, parentWebApp);  
    70.             });  
    71.         }  
    72.         catch (Exception ex)  
    73.         {  
    74.             throw ex;  
    75.         }  
    76.     }  
    77. }  

Deployment and Debug

  1. Right-click on the project name in your Solution Explorer and select Deploy.
  2. After successfully deploying it, activate the feature .
  3. Open Central Administration and select Manage Web Application.



  4. Select your web application.
  5. Select the "Manage Feature" tab on the ribbon control.



  6. The pop up window will display all your application scoped features. Find the feature that we have created here and activate it.



  7. After activating the feature, the timer job will be registered. To see a list of all the registered timer jobs, go to Central Administration and select "Monitoring->Review job definitions".



  8. Select the web application and find the job.

Timer Job Debugging

  1. For debugging the Execute() method, press CTRL+ALT+P and select the process "OWSTIMER.EXE" and click Attach.

Note: Whenever you make any code changes and re-deploy the solution, restart the Timer Service too. This will reduce your debugging time with strange issues.

Output

Conclusion

This article explained SharePoint timer jobs and the step-by-step development deployment and debugging of them.