Click here to Skip to main content
15,860,972 members
Articles / Productivity Apps and Services / Sharepoint
Tip/Trick

Create and Deploy Custom Timer Job Definition in SharePoint Programatically

Rate me:
Please Sign up or sign in to vote.
5.00/5 (26 votes)
8 Aug 2013CPOL5 min read 237.2K   19   23
Create and deploy custom timer job definition programatically in SharePoint.

What is Timer Job???

Timer Job is a background process that are run by SharePoint. In Central Administration, select Monitoring link from the main page, and then select Review job definitions link under the Timer Jobs section, then you will see the list of scheduled timer job definitions 

How to Create Custom Timer Job??

Problem

Execute a code in SharePoint at every 15 minutes and adds a new record to the Task list.

Solution

Need to create Timer job that will run automatically after every 15 minutes. Following are the steps to create custom timer job definition and deploy it.

Creating Job Definition Class

Step 1

Create an empty SharePoint project from visual studio 2010 or 2012 and give the name TimerJobApplication. You can give any name to this project but here in our example we are using this name. Press OK and select "Deploy as Farm Solution"

Image 1

Step 2

Add a new class to the project and give the name CustomTimerJob.cs. You can give any name to this class but here in our example I am using this name.

To do this, right click on the project name in solution explorer, select Add -> New Item. Under C# category select Code tab, select Class and give the class name.

TimerJobApplication -> Add -> New Item -> Class

Image 2

Step 3

Derive this CustomTimerJob from SPJobDefinition class.

You need to add following statements to do this.

C#
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

public class CustomTimerJob : SPJobDefinition
    {}

Step 4

Add following 3 constructors to your class.

C#
public CustomTimerJob() : base() { }

public CustomTimerJob(string jobName, SPService service): 
          base(jobName, service, null, SPJobLockType.None)
{
    this.Title = "Task Complete Timer";
}

public CustomTimerJob(string jobName, SPWebApplication webapp): 
        base(jobName, webapp, null, SPJobLockType.ContentDatabase)
{
    this.Title = "Task Complete Timer";
}

Step 5

Override the Execute() method to do your stuff. Whenever timer job executes, it will run the code written inside Execute() method.

C#
public override void Execute(Guid targetInstanceId)
{
    SPWebApplication webApp = this.Parent as SPWebApplication;
        SPList taskList = webApp.Sites[0].RootWeb.Lists["Tasks"];
        SPListItem newTask = taskList.Items.Add();
        newTask["Title"] = "New Task" + DateTime.Now.ToString();
        newTask.Update();
}

Here in our example, a new record will be added to Tasks list whenever timer job gets executes. You can write your own logic here.

Following is the complete code file for CustomTimerJob class.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Data;
using System.IO;
namespace TimerJobApplication
{
    public class CustomTimerJob : SPJobDefinition
    {
        public CustomTimerJob() : base() { }
        public CustomTimerJob(string jobName, SPService service)
                    : base(jobName, service, null, SPJobLockType.None)
            {
            this.Title = "Task Complete Timer";
            }
               public CustomTimerJob(string jobName, SPWebApplication webapp)
            : base(jobName, webapp, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Task Complete Timer";
        }
            public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication webApp = this.Parent as SPWebApplication;
            SPList taskList = webApp.Sites[0].RootWeb.Lists["Tasks"];
            SPListItem newTask = taskList.Items.Add();
            newTask["Title"] = "New Task" + DateTime.Now.ToString();
            newTask.Update();
        }
    }
}

Registering Timer Job Definition

Step 6

Add a new feature to register our custom timer job.

To do this, right click on Features inside project in solution explorer and click "Add Feature".

Image 3

Rename this feature to CustomTimerJobFeature.

Image 4

Image 5

Give Scope this feature to "Web Application".

For this, double click on CustomTimerJobFeature and choose scope "Web Application". Now press F4 so it will open property window of feature. Select False in "Activate on Default".

Image 6

Image 7

The reason behind selecting False is that we have to give feature scoped web application level and we dont want to activate this for all application. You have to activate this feature for the application for which you want to register timer job.

Step 7

Add Feature event receiver for this feature.

Right click on CustomTimerJobFeature and select "Add Event Receiver".

Write the following code to CustomTimerJobFeatureEventReceiver.cs class.

C#
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
namespace TimerJobApplication.Features.CustomTimerJobFeature
{
[Guid("e6ea0027-1187-419d-b357-306244d0ae37")]
    public class CustomTimerJobFeatureEventReceiver : SPFeatureReceiverimer
    {
        const string JobName = "New Task Timer";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                    SPSite site = properties.Feature.Parent as SPSite;
                    DeleteExistingJob(JobName, parentWebApp);
                    CreateJob(parentWebApp); 
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private bool CreateJob(SPWebApplication site)
        {
            bool jobCreated = false;
            try
            {
                CustomTimerJob job = new CustomTimerJob(JobName, site);
                SPMinuteSchedule schedule = new SPMinuteSchedule();
                schedule.BeginSecond = 0;
                schedule.EndSecond = 59;
                schedule.Interval = 15;
                job.Schedule = schedule;
 
                job.Update();                
            }
            catch (Exception)
            {
                return jobCreated;
            }
            return jobCreated;
        }
        public bool DeleteExistingJob(string jobName, SPWebApplication site)
        {
            bool jobDeleted = false;
            try
            {
                foreach (SPJobDefinition job in site.JobDefinitions)
                {
                    if (job.Name == jobName)
                    {
                        job.Delete();
                        jobDeleted = true;
                    }
                }
            }
            catch (Exception)
            {
                return jobDeleted;
            }
            return jobDeleted;
        }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
 
            lock (this)
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                        DeleteExistingTimerJobFromSite(this.JobName, parentWebApp);
                    });
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}

You can create different schedules as per your requirements. Here we have created SPMinuteSchedule for executing our job at every 15 minutes.

Other schedules you can also use as per your requirements. Following is the list of schedules.

Class Name Recurrence
SPYearlyScheduleRuns the timer job once per year
SPMonthlyScheduleRuns the timer job once per month on the specified day.
For example, the 15 of the month
SPMonthlyByDayScheduleRuns the timer job once per month on the specified day and week.
For example, the 3rd Friday of the month
SPWeeklyScheduleRuns the timer job once per week
SPDailySchdeduleRuns the timer job once every day
SPHourlyScheduleRuns the timer job once every hour
SPMinuteScheduleRuns the timer job once every n minutes
where n is the value in the Interval property
SPOneTimeScheduleRuns the timer job once

Deploying and Debugging

Right click on the project name in your solution explorer and select deploy.

After successfully deployed, you need to activate the feature manually because we have set property "Activate on Default" to False.

Open Central Administration and select manage web application.

Image 8

Select your web application and on ribbon control select "Manage Feature" tab then you will see the pop up window displaying all your application scoped features. Find the feature that we have created here and activate it.

When feature is activated, your timer job will be registered. To see list of all registered timer jobs, Go to central administration and select "Monitoring" section.

Image 9

Select "Review Job Definitions".

Image 10

You will be able to see all registered timer job. In this list you will also find our custom timer job listed.

Your code written in Execute() method will start executing at every 15 minutes (or whatever schedule you have set).

Debugging Timer job

Debugging timer job is quite different than debugging normal C# code. You need to attach "OWSTIMER.EXE".

To do this, after deploying the project, whenever you want to debug Execute() method, press CTRL+ALT+P and select the process "OWSTIMER.EXE" and click Attach. You can also open this dialog box manually from Debug menu.

Debug -> Attach to Process

Now, put the break-point at Execute() method so whenever your timer job executes, you can debug the code.

If you don't want to wait for timer job to be executed (15 minutes in our case), for testing purpose you can run timer job immediately from central administration. To do this select timer job listed in all Job Definitions and it will give you option to "Run" or "Disable" job as well as you can also set time schedule.

Important Note

Note that, whenever you change the logic or code inside Execute() method, you must restart the Timer service from Services.msc. If you just deploy without restarting service, it will not take your latest updates. So always have practice to restarting the "SharePoint Timer Service" from Services.msc.

If you still face any problem registering or deploying timer job, try uninstalling your assembly and restart the IIS and then deploy again.

To uninstall assembly, in "Run" type "assembly" and press enter. In list of assemblies, you will see the assembly of your project name. Select that and uninstall by right click.

To restart IIS, in "Run" type iisreset and press Enter.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Cybage Software pvt ltd
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionProblem moving from dev to staging Pin
Tomek Ulczak11-Aug-16 8:30
Tomek Ulczak11-Aug-16 8:30 
QuestionMy Vote of 5 Pin
Mohammad A. Amer1-Jun-15 1:10
professionalMohammad A. Amer1-Jun-15 1:10 
QuestionHelp me, timer job doesn't show in job definitions Pin
Member 1107267210-Sep-14 5:20
Member 1107267210-Sep-14 5:20 
AnswerRe: Help me, timer job doesn't show in job definitions Pin
arnab deb11-Mar-15 1:15
arnab deb11-Mar-15 1:15 
SuggestionRethrowing exceptions Pin
Bartho Bernsmann16-Jun-14 4:08
Bartho Bernsmann16-Jun-14 4:08 
QuestionThe Timer job i created and deployed is not available in Central Admin SP2013 Pin
Member 1087707410-Jun-14 20:13
Member 1087707410-Jun-14 20:13 
AnswerRe: The Timer job i created and deployed is not available in Central Admin SP2013 Pin
Lifestory12-Jun-14 22:18
Lifestory12-Jun-14 22:18 
GeneralRe: The Timer job i created and deployed is not available in Central Admin SP2013 Pin
Member 138977143-Jul-18 21:43
Member 138977143-Jul-18 21:43 
GeneralMy vote of 3 Pin
ZeroCode71-Jun-14 18:38
professionalZeroCode71-Jun-14 18:38 
SuggestionTypo errors Pin
ZeroCode71-Jun-14 18:37
professionalZeroCode71-Jun-14 18:37 
Questionmethod DeleteExistingTimerJobFromSite does not exist Pin
Logan Guo2-May-14 15:09
Logan Guo2-May-14 15:09 
AnswerRe: method DeleteExistingTimerJobFromSite does not exist Pin
Flávio Moreno Project Manager16-Jul-15 10:47
Flávio Moreno Project Manager16-Jul-15 10:47 
QuestionNot deployed Pin
dbjay16-Apr-14 16:27
professionaldbjay16-Apr-14 16:27 
QuestionWrong function calling in Code Block. Pin
Roshan Parmar27-Jan-14 21:09
Roshan Parmar27-Jan-14 21:09 
SuggestionVery helpful Pin
Member 104471295-Dec-13 3:19
Member 104471295-Dec-13 3:19 
QuestionProblem while debuging Pin
Girish Chandra M2-Dec-13 0:54
Girish Chandra M2-Dec-13 0:54 
AnswerRe: Problem while debuging Pin
Member 90179498-Jan-14 17:39
Member 90179498-Jan-14 17:39 
QuestionNice Article...Help me in MOSS 2007 Pin
soyeb9214-Nov-13 1:54
soyeb9214-Nov-13 1:54 
GeneralMy vote of 5 Pin
Member 1023710927-Aug-13 22:17
Member 1023710927-Aug-13 22:17 
GeneralRe: My vote of 5 Pin
Member 90179498-Jan-14 17:36
Member 90179498-Jan-14 17:36 
SuggestionRestart Timer service Pin
Giacomo Pozzoni8-Aug-13 7:15
Giacomo Pozzoni8-Aug-13 7:15 
AnswerRe: Restart Timer service Pin
Ravi Rachchh8-Aug-13 7:40
professionalRavi Rachchh8-Aug-13 7:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.