Click here to Skip to main content
15,867,141 members
Articles / Programming Languages / C#

SharePoint 2010: Create Custom Timer Jobs

Rate me:
Please Sign up or sign in to vote.
4.45/5 (9 votes)
13 Jun 2012CPOL6 min read 182.2K   2K   16   13
Creating a custom Timer Job in SharePoint.

Introduction

In this article we can try to create a custom Timer Job in SharePoint. The tools we are going to use are the following:

  • Visual Studio 2010
  • SharePoint DevTools from CodePlex

We can start with analyzing what a Timer Job is.

What is a Timer Job?

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

Image 1

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.

Image 2

Following is the list of some Timer Job definitions:

Image 3

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

Creating a Custom Timer Job Definition

Now we are ready with the basics to proceed with creating a Custom Timer Job.

Scenario

We have a list named Products which is custom template. Any new product arriving has to be posted to an SQL Server database so that the company website can show it to potential customers.

So the activities involved are the following:

  1. Create Products List inside SharePoint
  2. Create Product Table inside Database
  3. Create the Timer Job Definition
  4. Create Event Receiver
  5. Create the Database Insert method
  6. Deploy the Timer Job
  7. View the Results 

(Please note that the same scenario can be done through a combination of Workflow / Events / SSS)  

Step 1: Create Products List inside SharePoint

Here is the List Definition: (the list template with data is attached with the article)

Image 4

You can see that the core columns of the list are:

Column

Description

Title

The name of the Product

Description

About the Product

Price

The price of the Product

The HasPosted column determines whether the item is copied to the Products database. 

After installing the list from template you will can see it is having two items:

Image 5

Step 2: Create Product Table inside Database

Now we need to create the destination database and table.  Following is the table definition. (The table SQL is attached with the article.)

Image 6

<ph4>Step 3: Create the Timer Job

In this step we can go ahead and create the Timer Job.  For this you require Visual Studio 2010 and the SharePoint templates installed.

Open Visual Studio and create a new Empty SharePoint Project as shown below:

Image 7

In the next page select your server and use Deploy as Farm solution option:

Image 8

Click the Finish button after entering the options.

Now add a new class and derive it from SPJobDefinition as shown below:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace SPTimerJobExample
{
    public class ProductsJobDefinition : SPJobDefinition
    {
    }
}

Now replace the above file with the following content:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace SPTimerJobExample
{
    public class ProductsTimerJob : SPJobDefinition
    {
        public ProductsTimerJob()
            : base()
        {

        }

        public ProductsTimerJob(string jobName, SPService service, 
               SPServer server, SPJobLockType lockType)
               : base(jobName, service, server, lockType)
        {
            this.Title = "Products Timer Job";
        }

        public ProductsTimerJob(string jobName, SPWebApplication webapp)
            : base(jobName, webapp, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Products Timer Job";
        }

        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication webapp = this.Parent as SPWebApplication;
            SPContentDatabase contentDb = webapp.ContentDatabases[targetInstanceId];

            SPList list = contentDb.Sites[0].RootWeb.Lists["Products"];

            CopyItems(list);
        }

        private void CopyItems(SPList list)
        {
            foreach (SPListItem item in list.Items)
            {
                bool hasPosted = (bool)item["HasPosted"];

                if (!hasPosted)
                {
                    new DbManager().Insert(item);

                    item["HasPosted"] = true;
                    item.Update();
                }
            }
        }
    }
}

The above code is performing the following activities:

  1. Get the list of items from Products where HasPosted is false.
  2. Insert the Product into database.
  3. Mark the item HasPosted to true.

We need to include the DbManager class file and will be done in the upcoming step.

Step 4: Create Event Receiver

Now we have to create an event receiver which performs the installation or un-installation of the Job Definition.

In the Solution Explorer right click on Feature and use the Add Feature item.

Image 9

In the appearing dialog change the title to Products Job Definition and the Scope to Site.

Image 10

Now right click on the Solution Explorer > Feature 1 and click Add Event Receiver

Image 11

Inside the class content of Feature1.EventReceiver.cs place the following code:

C#
const string JobName = "Products Timer Job";

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPSite site = properties.Feature.Parent as SPSite;

    DeleteJob(site); // Delete Job if already Exists

    CreateJob(site); // Create new Job
}

private static void DeleteJob(SPSite site)
{
    foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
       if (job.Name == JobName)
            job.Delete();
}

private static void CreateJob(SPSite site)
{
    ProductsTimerJob job = new ProductsTimerJob(JobName, site.WebApplication);

    SPMinuteSchedule schedule = new SPMinuteSchedule();
    schedule.BeginSecond = 0;
    schedule.EndSecond = 5;
    schedule.Interval = 5;

    job.Schedule = schedule;
    job.Update();
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    DeleteJob(properties.Feature.Parent as SPSite); // Delete the Job
}

You need to add the using as well:

C#
using Microsoft.SharePoint.Administration;

Step 5: Create the Database Insert Method

In this step we can complete the DbManager class file.  Here we are using Entity Framework associated with .Net 3.5 version.

For this add a new Entity Data Model into the project and map to the Product table which we have created in previous step.

Image 12

Now create a class file named DbManage.cs and replace it with the following content:

C#
using System;

namespace SPTimerJobExample
{
    public class DbManager
    {
        public void Insert(Microsoft.SharePoint.SPListItem item)
        {
            using (ProductionModel context = new ProductionModel(GetConnectionString()))
            {
                Product product = new Product();
                product.Title = item["Title"].ToString();
                product.Description = item["Description"].ToString();
                product.Url = item["Url"].ToString();
                product.Price = (double)item["Price"];
                product.PostedOn = DateTime.Today;

                context.AddToProducts(product);

                context.SaveChanges();
            }
        }

        public string GetConnectionString()
        {
            string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
            {
                Metadata = "res://*",
                Provider = "System.Data.SqlClient",
                ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
                {
                    InitialCatalog = "YOUR-DB-NAME-HERE",
                    DataSource = @"YOUR-SERVER-NAME-HERE",
                    IntegratedSecurity = false,
                    UserID = "YOUR-USER-ID-HERE",   
                    Password = "YOUR-PASSWORD-HERE",          
                }.ConnectionString
            }.ConnectionString;

            return connectionString;
        }
    }
}

The above code contains the Insert() method to insert new record into the Product table.

For the time being I am hard coding the connection string.  You need to specify the correct user credentials in the GetConnectionString() method.

Note: Please note that the connection string is loaded from the executing application’s configuration file.  In the case of Timer Jobs the configuration file will be OWSTIMER.exe.config residing in the 14hive folder.

Step 6: Deploy the Timer Job

Now we are ready to deploy the Timer Job into the SharePoint Site.  For this right click on the solution and click the Deploy option.

Image 13

If you get the Deploy Succeeded message we are good.

Step 7: View the Results

Now we can go to the Central Administration to see our Timer Job.  For this open Central Administration web site and go to Monitoring > Review Job Definitions

Image 14

On clicking the Review Job Definitions link you can see our item as shown below:

Image 15

Click on the item and in the appearing page click the button Run Now

Image 16

You can see that the Timer Job is set for 5 Minutes according to our code.

Now we can go back to the Products list and see that the HasPosted is set to True.

Image 17

Going to the SQL Server Table we can see both the records are inserted there.

Image 18

Troubleshooting Tips

While developing timer jobs, you might need to delete the assembly and feature as well.  Please note the following points for troubleshooting guidance:

  • Features are deployed to the 14hive folder
  • The assembly gets deployed to GAC folder
  • You can use RETRACT option from  Visual Studio
  • You can use GACUTIL to uninstall the assembly
  • You can remove the Feature from 14hive folder

For troubleshooting the Farm Solutions or User Solutions you can use:

  • Central Administration > System Settings > Manage Farm Solutions
  • Central Administration > System Settings > Manage User Solutions

Image 19

You can Retract or undo the last Retract schedule there.

For checking the Job Status or History you can use:

  • Central Administration > Monitoring >  Check Job Status > Timer Job Status
  • Central Administration > Monitoring >  Check Job Status >  Timer Job History

These screens will show the Success / Failure status of the jobs and any errors associated.  For example an invalid connection string problem is identified as shown below:

Image 20

Debugging Tips

In some cases the Timer Service hold the old version of assembly.  So the new changes you have done through Visual Studio may not get reflect immediately.  You can change the assembly version and view the GAC to ensure the correct version was deployed.

Image 21

Plus you can restart the SharePoint 2010 Timer Service from services.msc

Image 22

Note: In the case of Integrated Security as True in connection strings, the authenticated user would be the Service Account user assigned in the service.

References

Summary

In this article we have explored the Timer Job feature of SharePoint and creating a custom timer job.  Following are the key points to be remembered:

  • Timer Jobs can be scheduled for automating jobs inside SharePoint 2010
  • SPJobDefinition is the base class for Timer Job
  • Create Event Receiver Feature to create or delete the timer job
  • SPFeatureReceiver is the base class for the event receiver
  • The feature gets deployed in the 14hive folder
  • OWSTIMER.EXE is the process executing Timer Jobs

The associated source code along with the list template with data is attached.  You can download and try running it.

License

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


Written By
Architect
United States United States
Jean Paul is a Microsoft MVP and Architect with 12+ years of experience. He is very much passionate in programming and his core skills are SharePoint, ASP.NET & C#.

In the academic side he do hold a BS in Computer Science & MBA. In the certification side he holds MCPD & MCTS spanning from .Net Fundamentals to SQL Server.

Most of the free time he will be doing technical activities like researching solutions, writing articles, resolving forum problems etc. He believes quality & satisfaction goes hand in hand.

You can find some of his work over here. He blogs at http://jeanpaulva.com

Comments and Discussions

 
QuestionSharepoint Timer job Pin
createanand26-Jan-15 22:23
createanand26-Jan-15 22:23 
QuestionError Message The underlying provider failed on Open. Pin
Member 104669919-Feb-14 13:43
Member 104669919-Feb-14 13:43 
QuestionProblem while debuging Pin
Girish Chandra M2-Dec-13 0:54
Girish Chandra M2-Dec-13 0:54 
QuestionGood one!! Pin
Vasan Js30-Sep-13 4:05
Vasan Js30-Sep-13 4:05 
AnswerRe: Good one!! Pin
Jean Paul V.A30-Sep-13 8:08
Jean Paul V.A30-Sep-13 8:08 
QuestionVery nice article Pin
Leonid Fofanov15-Jul-13 11:19
Leonid Fofanov15-Jul-13 11:19 
AnswerRe: Very nice article Pin
Jean Paul V.A15-Jul-13 11:25
Jean Paul V.A15-Jul-13 11:25 
You are welcome dear friend!
Jean.

GeneralIssue Pin
bilodeausp8-Jul-13 9:38
bilodeausp8-Jul-13 9:38 
QuestionNice One Pin
Sreejith Gopinathan17-Feb-13 1:41
Sreejith Gopinathan17-Feb-13 1:41 
AnswerRe: Nice One Pin
Jean Paul V.A17-Feb-13 3:46
Jean Paul V.A17-Feb-13 3:46 
GeneralVery helpful! Pin
jbcollins21-Aug-12 9:29
jbcollins21-Aug-12 9:29 
GeneralRe: Very helpful! Pin
Jean Paul V.A21-Aug-12 9:34
Jean Paul V.A21-Aug-12 9:34 
GeneralRe: Very helpful! Pin
Ted D Wagner28-Jul-14 8:23
Ted D Wagner28-Jul-14 8:23 

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.