By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,967 Members | 815 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

How to Create & Deploy a SharePoint 2007 Timer Job

P: 2
With SharePoint timer jobs you can create & execute processes on a daily / hourly / minutely basis.
After deployment, the timer job definition executes your custom code.

The easiest (and more common) way to deploy a timer job is by feature.
When the feature is being activated, a custom code on the "FeatureActivated" method should install the timer job.

This is a complete example of how to create and deploy a timer job definition.
  1. In "Visual Studio", Create new 'WSPBuilder' project.
  2. Now, we will add the feature that will install the timer job definition.
  3. Right click on the project -> 'Add' -> 'New Item'.
  4. Under 'WSPBuilder' select 'Feature with Receiver'.
  5. This will create a new feature with a class that implements the feature installation / activation methods.
  6. When the dialog box appears, type your timer job name and description.
  7. Finally, select 'WebApplication' in the 'Scope' section.
  8. * Note: There are few more scopes that you can select.
    • "Farm": the feature will be installed on the entire farm.
    • "Site": the feature will be installed on a single site collection (and all sub-sites).
    • "Web": the feature will be installed on a specific web site (sub-site).
This will create 3 files in your project:
  1. feature.xml - contains definitions of the feature.
  2. elements.xml
  3. TimerJobInstaller.cs - contains override methods for the installation / activation events.
In the method 'FeatureActivated' we will later write the code that installs the timer job.
Now, we will create the timer job itself.
Right click on the 'FeatureCode' folder, 'Add' -> 'Class'.
Type the name of your timer job (I've called it with the singular name: 'MyTimerJob.cs').
This will add a simple class. In order that this class will act as timer job, it should inherit the 'SPJobDefinition' class.
Check this complete code of the 'MyTimerJob.cs' class:
Expand|Select|Wrap|Line Numbers
  1.     using System;
  2.     using System.Collections.Generic;
  3.     using System.Text;
  4.     using Microsoft.SharePoint.Administration;
  5.     using System.IO;
  6.     namespace WSPBuilderProject1.FeatureCode
  7.     {
  8.         public class MyTimerJob : SPJobDefinition
  9.         {
  10.             public MyTimerJob() : base()
  11.             {
  12.                 this.Title = "My Timer Job";
  13.             }
  14.  
  15.             public MyTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
  16.                 : base(jobName, service, server, targetType)
  17.             {
  18.                 this.Title = "My Timer Job";
  19.             }
  20.  
  21.             public MyTimerJob(string jobName, SPWebApplication webApplication)
  22.                 : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
  23.             {
  24.                 this.Title = "My Timer Job";
  25.             }
  26.  
  27.             public override void Execute(Guid contentDbId)
  28.             {
  29.                 //TODO: write here the code of your job!
  30.             }
  31.         }
  32.     }

This class overrides the method 'Execute' that will execute the job's custom code!
In this method you can write whatever you need.
For example: code that delete items from lists, create sites, copy documents from document libraries, etc...
Now that our timer job is ready, we should return to the feature receiver class ('TimerJobInstaller.cs') and there we should write the code that installs the job.
Expand|Select|Wrap|Line Numbers
  1.     using System;
  2.     using System.Collections.Generic;
  3.     using System.Text;
  4.     using Microsoft.SharePoint;
  5.     using Microsoft.SharePoint.Administration;
  6.     using WSPBuilderProject1.FeatureCode;
  7.  
  8.     namespace WSPBuilderProject1
  9.     {
  10.         class TimerJobInstaller : SPFeatureReceiver
  11.         {
  12.             const string SYNC_JOB_NAME = "My_Timer_Job";
  13.             public override void FeatureActivated(SPFeatureReceiverProperties properties)
  14.             {
  15.                 try
  16.                 {
  17.                     SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
  18.  
  19.                     // make sure the job isn't already registered
  20.                     foreach (SPJobDefinition job in webApp.JobDefinitions)
  21.                     {
  22.                         if (job.Name == SYNC_JOB_NAME)
  23.                             job.Delete();
  24.                     }
  25.  
  26.                     // install the job
  27.                     MyTimerJob myJob = new MyTimerJob(SYNC_JOB_NAME, webApp);
  28.  
  29.                     // Set the schedule - nightly at 23:00 pm
  30.                     //SPSchedule customSchedule = SPSchedule.FromString("daily at 23:00");
  31.                     //syncJob.Schedule = customSchedule;
  32.  
  33.                     //Set the schedule - every minute
  34.                     //SPMinuteSchedule minuteSchedule = new SPMinuteSchedule();
  35.                     //minuteSchedule.BeginSecond = 0;
  36.                     //minuteSchedule.EndSecond = 59;
  37.                     //minuteSchedule.Interval = 3;
  38.                     //syncJob.Schedule = minuteSchedule;
  39.  
  40.                     //Set the schedule - hourly between 0 and 59
  41.                     SPSchedule schedule = SPSchedule.FromString("hourly between 0 and 59");
  42.                     myJob.Schedule = schedule;
  43.                     myJob.Update();
  44.                 }
  45.                 catch (Exception e)
  46.                 {
  47.                 }
  48.             }
  49.  
  50.             public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
  51.             {
  52.                 SPSite site = properties.Feature.Parent as SPSite;
  53.  
  54.                 // delete the job
  55.                 foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
  56.                 {
  57.                     if (job.Name == SYNC_JOB_NAME)
  58.                         job.Delete();
  59.                 }
  60.             }
  61.  
  62.             public override void FeatureInstalled(SPFeatureReceiverProperties properties)
  63.             {
  64.             }
  65.  
  66.             public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
  67.             {
  68.             }
  69.         }
  70.     }
This code will install the timer job and will set its schedule to be hourly (every hour).
I've added in comments more ways to schedule the timer job.

Note that I've override also the 'FeatureDeactivating' method - this will delete the job when the feature would be deactivated.

That's it! Our timer job is ready for deployment.
To deploy the timer job, we will need to install & activate the feature. Then - the feature will do the rest (install the timer job through the code we written in the 'FeatureActivated' method).
  1. First we need to copy the DLL to the GAC.
  2. Build your project.
  3. Right click on the project -> 'WSPBuilder' -> 'Copy to GAC'.
  4. Then we should copy the feature to the FEATURES directory in the 12 hive.
  5. Right click on the project -> 'WSPBuilder' -> 'Copy to 12 hive'.
  6. Now we should install and activate the feature.
  7. Open cmd.exe and type cd "Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN". Then type these 2 commands:
    • stsadm -o installfeature -filename TimerJobInstaller\feature.xml -force
    • stsadm -o activatefeature -filename TimerJobInstaller\feature.xml -url http://il-moss-dev5:6680/sites/site1
    The first command installs the feature. The second command activates it. Upon activation, the timer job will be installed.


You can now see the new installed timer job in the "Central Administration".
Central Administration > Operations > Timer Job Definitions.
Nov 21 '10 #1
Share this Article
Share on Google+
1 Comment


P: 1
I have created a Timer Job and deployed the wsp to the central admin. The feature is installed and activated fine. I don't get any error. But i can't see the timer job in the Timer job list in central admin. I dont see the feature in the site collection feature either.

1)I did install and activate the features using STSADM commands.
2) The Timer job does not appear under Job Definitions in sharepoint manager. The feature however does appear under the Feature definitions in sharepoint manager

The Webapplication has three site collections and each site collection has a separate database database

MY code is as follows
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Data.SqlClient;
  5. using Microsoft.SharePoint;
  6. using Microsoft.SharePoint.Administration;
  7. namespace TestTimer
  8. {
  9.     public class TestTimerJob:SPJobDefinition
  10.     {
  11.         public TestTimerJob() : base() 
  12.         {
  13.  
  14.         }
  15.         public TestTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
  16.             : base(jobName, service, server, targetType)
  17.         {
  18.             this.Title = "Test Timer Job";
  19.  
  20.         }
  21.         public TestTimerJob(string jobName, SPWebApplication webApplication)
  22.             : base(jobName, webApplication, null, SPJobLockType.Job)
  23.         {
  24.             this.Title = "Test Timer Job";
  25.         }
  26.  
  27.         public override void Execute(Guid targetInstanceId)
  28.         {
  29.             try
  30.             {
  31.                 SendEmail();
  32.             }
  33.             catch (Exception ex)
  34.             {
  35.                 LogError(ex.InnerException.ToString(), ex.StackTrace + ex.Source);
  36.             } 
  37.         }
  38.         private void SendEmail()
  39.         {
  40.             try
  41.             {
  42.                 System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
  43.  
  44.                 //msg.To.Add(ToEmailAddress);
  45.                 msg.To.Add("****");
  46.                 msg.From = new System.Net.Mail.MailAddress(""********";");
  47.                 msg.Subject = "Subject";
  48.  
  49.                 msg.IsBodyHtml = true;
  50.                 string EmailBody = " <b>Welcome to Send an Email!!</b><p> Example.<BR>";
  51.                 msg.Body = EmailBody;
  52.                 string smtp = "***";
  53.                 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtp);
  54.                 System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
  55.                 NetworkCred.UserName = "********";
  56.                 NetworkCred.Password = "********";
  57.                 NetworkCred.Domain = "********";
  58.                 client.Credentials = NetworkCred;
  59.                 client.Send(msg);
  60.             }
  61.             catch (Exception ex)
  62.             {
  63.  
  64.                 LogError(ex.InnerException.ToString(), ex.StackTrace);
  65.             }
  66.  
  67.  
  68.  
  69.  
  70.  
  71.         }
  72.  
  73.  
  74.     }
  75. }
Feature Reciever code below
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Microsoft.SharePoint;
  5. using Microsoft.SharePoint.Administration;
  6. using System.Data.SqlClient;
  7. namespace TestTimer
  8. {
  9.     class TestTimerReceiver : SPFeatureReceiver
  10.     {
  11.         const string SYNC_JOB_NAME = "My_Timer_Job";
  12.         public override void FeatureActivated(SPFeatureReceiverProperties properties)
  13.         {
  14.             try
  15.             {
  16.                 SPWebApplication webapp = (SPWebApplication)properties.Feature.Parent;
  17.                 foreach (SPJobDefinition job in webapp.JobDefinitions)
  18.                 {
  19.                     if (job.Name.ToLower()==SYNC_JOB_NAME.ToLower())
  20.                     {
  21.                         job.Delete();
  22.                     }
  23.                 }
  24.  
  25.  
  26.                 TestTimerJob timerJob = new TestTimerJob(SYNC_JOB_NAME, webapp);
  27.                 SPMinuteSchedule schedule = new SPMinuteSchedule();
  28.                 schedule.BeginSecond = 0;
  29.                 schedule.EndSecond = 59;
  30.                 schedule.Interval = 5;
  31.                 timerJob.Schedule = schedule;
  32.                 timerJob.Update();
  33.             }
  34.             catch (Exception ex)
  35.             {
  36.  
  37.             }
  38.         }
  39.  
  40.         public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
  41.         {
  42.             try
  43.             {
  44.                 SPWebApplication webapp = (SPWebApplication)properties.Feature.Parent;
  45.                 foreach (SPJobDefinition  job in webapp.JobDefinitions)
  46.                 {
  47.                     if (job.Name.ToLower()==SYNC_JOB_NAME.ToLower())
  48.                     {
  49.                         job.Delete();
  50.                     }
  51.                 }
  52.             }
  53.             catch (Exception ex)
  54.             {
  55.  
  56.             }
  57.         }
  58.  
  59.         public override void FeatureInstalled(SPFeatureReceiverProperties properties)
  60.         {
  61.  
  62.         }
  63.  
  64.         public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
  65.         {
  66.  
  67.         }
  68.     }
  69. }
and Feature .xml below
Expand|Select|Wrap|Line Numbers
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Feature  Id="b4fa9cf0-dba9-4206-a37c-e707af6199f9"
  3.           Title="TestTimerReceiver"
  4.           Description="Description for TestTimerReceiver"
  5.           Version="12.0.0.0"
  6.           Hidden="FALSE"
  7.           Scope="Site"
  8.           DefaultResourceFile="core"
  9.           ReceiverAssembly="TestTimer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7f9249145d98c2ad"
  10.           ReceiverClass="TestTimer.TestTimerReceiver"
  11.  
  12.  
  13.  
  14.           xmlns="http://schemas.microsoft.com/sharepoint/">
  15.   <ElementManifests>
  16.     <ElementManifest Location="elements.xml"/>
  17.   </ElementManifests>
  18. </Feature>
Jul 17 '13 #2