Wednesday 23 May 2012

How to create a Custom Timer job in SharePoint(CODE)

When we want to run a task (like sending emails or deleting the list items etc. . .  )  in Daily basis or in Hourly basis then we can use a Timer job to this task .To see the  timer job you can move to the Central Administrations then click on the operations tab,  then in the Global Configuration section you can see the Timer job status and timer job definition. In timer job definition you can get the details of the timer job i.e.  the  title , the web application to which it is attached   and the schedule type i.e.  Daily, Weekly or hourly basis. To get the status of the timer job go to the timer job status, here you can view status.
Steps To create a custom timer job:
  1. We need to create a class that inherits the SPJobDefinition Class. Then we need add the constructor s and the Execute () method.
   namespace TestTimerJob {
                 public class CustomTimerJob : SPJobDefinition{ 
                              public CustomTimerJob (): base(){
                               }
                              /// <summary>
                             /// Initializes a new instance of the TaskJob class.
                            /// </summary>
                           /// <param name="jobName">Name of the job.</param>
                          /// <param name="service">The service.</param>
                         /// <param name="server">The server.</param>
                        /// <param name="targetType">Type of the target.</param>
                       public CustomTimerJob (string jobName, SPService service, SPServer server, SPJobLockType targetType)
                                      : base (jobName, service, server, targetType) {
                        }   
                        /// <summary>
                      /// Initializes a new instance of the TaskJob class.
                     /// </summary>
                    /// <param name="jobName">Name of the job.</param>
                   /// <param name="webApplication">The web application.</param>
                  public CustomTimerJob(string jobName, SPWebApplication webApplication)
                                        : base (jobName, webApplication, null, SPJobLockType.ContentDatabase) {
                          this.Title = "Test Timer Job";    
                   }
                  /// <summary>
                 /// Executes the specified content db id.
                /// </summary>
                /// <param name="contentDbId">The content db id.</param>
                public override void Execute (Guid contentDbId) 
                {
                            //Do the Operation which u want to perform
                 }
         }
     }


2. As we are going to deploy the timer job as a feature so we need to create another class which will implement the SPFeatureReceiver class. This class contains the event handlers. Here we can define the task which we are going to do when a feature will be installed, activated, deactivated and uninstalled.
namespace TestTimerJob { 
 class TaskJobInstaller:SPFeatureReceiver {  
    /// <summary>
    /// Occurs after a Feature is installed.
    /// </summary>
    /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the   properties of the event.</param>
    public override void FeatureInstalled (SPFeatureReceiverProperties properties) {
    }
    /// <summary>
    /// Occurs when a Feature is uninstalled.
    /// </summary>
    /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>
    public override void FeatureUninstalling (SPFeatureReceiverProperties properties) {
    }
    /// <summary>
    /// Occurs after a Feature is activated.
    /// </summary>
    /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        // register the the current web
        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 == "Test Timer Job")
                job.Delete();
        } 
        // install the job
        TaskJob taskJob = new TaskJob("Test Timer Job", site.WebApplication); 
        //To perform the task on daily basis
        SPDailySchedule schedule = new SPDailySchedule();
        schedule.BeginHour = 2;
        schedule.BeginMinute = 10;
        schedule.BeginSecond = 0;
        schedule.EndHour = 2;
        schedule.EndMinute = 20;
        schedule.EndSecond = 0;
        taskJob.Schedule = schedule; 
        taskJob.Update();
    }     
    /// <summary>
    /// Occurs when a Feature is deactivated.
    /// </summary>
    /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>
    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 == "Test Timer Job")
          job.Delete();
      }
    }
  }
}
3. Create a feature.xml file to deploy the feature.
 <?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
         Id="DA0DAC0D-B1C3-4832-91ED-A20DEDC16BD4"
         Title="Test Timer job"
         Description="Performs the scheduled SHP tasks"
         Scope="Site"
         Hidden="FALSE"
         Version="1.0.0.0"
         ReceiverAssembly="TestTimerJob, Version=1.0.0.0, Culture=neutral, PublicKeyToken=293e555b2fe2e92a"
         ReceiverClass="TestTimerJob.TaskJobInstalle">
</Feature>
4, Create a folder inside.  C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\FEATURES\  and place this file inside the folder.
  Now you can install the feature using the STSADM command .After installing the feature when you activate this feature on a SharePoint site then you will be able to see the Timer job in the Timer job definition inside the central administrator. 

1 comment: