What is a Timer Job?

A Timer Job is a periodically executed task inside SharePoint Server. It provides us a task execution environment.

For example, we can execute tasks like: sending emails every hour, data updating every day, creating reports every week, etc.

Default Timer Jobs inside SharePoint

There are many timer jobs inside SharePoint which do internal tasks like:

  • Send emails
  • Validate sites
  • Delete unused sites
  • Health analysis
  • Product versioning
  • Diagnostics

These tasks will having execution periods like:

  • Minute
  • Hour
  • Day
  • Week
  • Month

Manage Timer Jobs

You can see all Timer Jobs from Central Administration > Monitoring > Manager Timer Jobs.

Following is the list of some Timer Job definitions:

You can select each1 Job Definition and change the schedule or disable it.

 

 

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”

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

Step 3

Derive this CustomTimerJob from SPJobDefinition class.

You need to add following statements to do this.

Collapse | Copy Code

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

 

public class CustomTimerJob : SPJobDefinition

{}

Step 4

Add following 3 constructors to your class.

Collapse | Copy Code

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 insideExecute() method.

Collapse | Copy Code

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.

Collapse | Copy Code

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”.

Rename this feature to CustomTimerJobFeature.

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”.

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.

Collapse | Copy Code

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
SPYearlySchedule Runs the timer job once per year
SPMonthlySchedule Runs the timer job once per month on the specified day.
For example, the 15 of the month
SPMonthlyByDaySchedule Runs the timer job once per month on the specified day and week.
For example, the 3rd Friday of the month
SPWeeklySchedule Runs the timer job once per week
SPDailySchdedule Runs the timer job once every day
SPHourlySchedule Runs the timer job once every hour
SPMinuteSchedule Runs the timer job once every n minutes
where n is the value in the Interval property
SPOneTimeSchedule Runs 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.

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.

Select “Review Job Definitions”.

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 fromServices.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.

 

Advertisements