Timer Jobs in SharePoint 2010

Timer Jobs in SharePoint 2010



What is a Timer Job?

Timer Job is a periodically executed task inside SharePoint Server. It provides us a task execution environment.
For example, we can execute tasks like: update list item everyday, send email every hour

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
see this link for more details

          Here I will explain how to create a SharePoint timer job using visual studio.Do the following steps.

Step 1 : 

Open visual studio->New Project->SharePoint->
Empty SharePoint Project->Give Project name(here I gave as TimerJobExample)->
click Next->Give your url->Deploy as Farm solution->click Finish

Step 2: 

Add a Class file in this program, for that->Go to Solution Explorer->Right click your project->Add New Item->Select Class ->Name it as Execution.cs
  • Add the following Name Spaces
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
Add the following code to the class.We derive this class from SPJobDefinition class
Execution.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace TimerJobExample
{
   public class Execution : SPJobDefinition
   { 
       public Execution () : base()
       { }

       public Execution(string jobName, SPService service, SPServer server, SPJobLockType targetType)
           : base(jobName, service, server, targetType)
       { }

       public Execution(string jobName, SPWebApplication webApplication)
           : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
       { this.Title = "Timer Job For TimerJobExample"; }

       public override void Execute(Guid contentDbId)
       {
           // get a reference to the current site collection's content database 
           SPWebApplication webApplication = this.Parent as SPWebApplication;
           SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
  // get a reference to the "TimerJobList" list in the RootWeb of the first site collection in the content database 
           SPList TimerJobList = contentDb.Sites[0].RootWeb.Lists["TimerJobList"];  // SharePoint List Name
           // create a new Item, Add the Title and other column
           SPListItem newItem = TimerJobList.Items.Add();
           newItem["Title"] = "TimerJob Title1";
           newItem["Column1"] = "Sample Data";
           newItem.Update();
       }
   }
}

Step 3 : 

Go to solution Explorer->Features->Add Feature->Rename your
Feature Name as your Program Name(Here I gave as TimerJobExample)

Step 4 : 

Right click your Feature->Add Event Receiver
(Event receiver which performs the installation or un-installation of the Job Definition)

Step 5 : 

  • Add the folowing name space in the Event receiver page
    using Microsoft.SharePoint.Administration;
We are inheriting Event receiver from SpFeatureReceiver class, and using event handlers like FeatureActivated(asynchronous events),FeatureDeactivating (synchronous events).
In this Event Receiver Page There is one Guid will be there, don't change that ID.
After that Uncomment the events in that page-> FeatureActivated & FeatureDeactivating events
And give any name for Timer Job here.See the Below image

Add the Following Code in the events FeatureActivated & FeatureDeactivating events
TimerJobExample.EventReceiver.cs :
 public class TimerJobExampleEventReceiver : SPFeatureReceiver
  {
      const string List_JOB_NAME = "TimerJobExample";
      // Uncomment the method below to handle the event raised after a feature has been activated. 
      public override void FeatureActivated(SPFeatureReceiverProperties properties)
         {
             SPSite site = properties.Feature.Parent as SPSite;

             // make sure the job isn't already registered
             foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
              {
                 if (job.Name == List_JOB_NAME)
                     job.Delete();
              }

            // install the job
            Execution listLoggerJob = new Execution(List_JOB_NAME, site.WebApplication);
            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 15;
            listLoggerJob.Schedule = schedule;
            listLoggerJob.Update();
        }

 // Uncomment the method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            // delete the job
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == List_JOB_NAME)
                    job.Delete();
            }
        }
}

Step 6 : 

Deploy the Program.
If you get the following Error
error occurred in deployment step 'activate features' object reference not set
Double click your Feature and check the Scope,If it is web then
change it as Site,save and deploy
Thats all you have created that timer job.


Note: Worker Process used for debug timer job is "OWSTIMER.exe"

Step 7 : 

To check timer job
central admin-> Monitoring->Timer Jobs->Review job definitions
There you can see your custom timer job Name.

Step 8 :

Here you can change your timer duration, or you can Disable timer.

Step 9 : 

Now go to your List and check that data,That  will be added in a particular duration

If timer not started then Reset iis, restart the services(SharePoint 2010 Timer).

For Reference codeproject Link , Link2

Comments

Popular posts from this blog

Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

A type named 'SP.Data. could not be resolved by the model error

Add content type to SharePoint List/Library using REST API