How to Create & Deploy a SharePoint 2007 Timer Job

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Eran Hefer
    New Member
    • Nov 2010
    • 2

    How to Create & Deploy a SharePoint 2007 Timer Job

    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 "FeatureActivat ed" 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. TimerJobInstall er.cs - contains override methods for the installation / activation events.

    In the method 'FeatureActivat ed' 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 'SPJobDefinitio n' class.
    Check this complete code of the 'MyTimerJob.cs' class:
    Code:
        using System;
        using System.Collections.Generic;
        using System.Text;
        using Microsoft.SharePoint.Administration;
        using System.IO;
        namespace WSPBuilderProject1.FeatureCode
        {
            public class MyTimerJob : SPJobDefinition
            {
                public MyTimerJob() : base()
                {
                    this.Title = "My Timer Job";
                }
    
                public MyTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
                    : base(jobName, service, server, targetType)
                {
                    this.Title = "My Timer Job";
                }
    
                public MyTimerJob(string jobName, SPWebApplication webApplication)
                    : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
                {
                    this.Title = "My Timer Job";
                }
    
                public override void Execute(Guid contentDbId)
                {
                    //TODO: write here the code of your job!
                }
            }
        }

    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 ('TimerJobInsta ller.cs') and there we should write the code that installs the job.
    Code:
        using System;
        using System.Collections.Generic;
        using System.Text;
        using Microsoft.SharePoint;
        using Microsoft.SharePoint.Administration;
        using WSPBuilderProject1.FeatureCode;
    
        namespace WSPBuilderProject1
        {
            class TimerJobInstaller : SPFeatureReceiver
            {
                const string SYNC_JOB_NAME = "My_Timer_Job";
                public override void FeatureActivated(SPFeatureReceiverProperties properties)
                {
                    try
                    {
                        SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
    
                        // make sure the job isn't already registered
                        foreach (SPJobDefinition job in webApp.JobDefinitions)
                        {
                            if (job.Name == SYNC_JOB_NAME)
                                job.Delete();
                        }
    
                        // install the job
                        MyTimerJob myJob = new MyTimerJob(SYNC_JOB_NAME, webApp);
    
                        // Set the schedule - nightly at 23:00 pm
                        //SPSchedule customSchedule = SPSchedule.FromString("daily at 23:00");
                        //syncJob.Schedule = customSchedule;
    
                        //Set the schedule - every minute
                        //SPMinuteSchedule minuteSchedule = new SPMinuteSchedule();
                        //minuteSchedule.BeginSecond = 0;
                        //minuteSchedule.EndSecond = 59;
                        //minuteSchedule.Interval = 3;
                        //syncJob.Schedule = minuteSchedule;
    
                        //Set the schedule - hourly between 0 and 59
                        SPSchedule schedule = SPSchedule.FromString("hourly between 0 and 59");
                        myJob.Schedule = schedule;
                        myJob.Update();
                    }
                    catch (Exception e)
                    {
                    }
                }
    
                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 == SYNC_JOB_NAME)
                            job.Delete();
                    }
                }
    
                public override void FeatureInstalled(SPFeatureReceiverProperties properties)
                {
                }
    
                public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
                {
                }
            }
        }
    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 'FeatureDeactiv ating' 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 'FeatureActivat ed' 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\B IN". Then type these 2 commands:
      • stsadm -o installfeature -filename TimerJobInstall er\feature.xml -force
      • stsadm -o activatefeature -filename TimerJobInstall er\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.
    Last edited by Frinavale; Oct 12 '11, 02:56 AM. Reason: Added code tags and lists to the article.
  • johnmathew
    New Member
    • Jul 2013
    • 1

    #2
    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
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Data.SqlClient;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    namespace TestTimer
    {
        public class TestTimerJob:SPJobDefinition
        {
            public TestTimerJob() : base() 
            {
                  
            }
            public TestTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
                : base(jobName, service, server, targetType)
            {
                this.Title = "Test Timer Job";
            
            }
            public TestTimerJob(string jobName, SPWebApplication webApplication)
                : base(jobName, webApplication, null, SPJobLockType.Job)
            {
                this.Title = "Test Timer Job";
            }
    
            public override void Execute(Guid targetInstanceId)
            {
                try
                {
                    SendEmail();
                }
                catch (Exception ex)
                {
                    LogError(ex.InnerException.ToString(), ex.StackTrace + ex.Source);
                } 
            }
            private void SendEmail()
            {
                try
                {
                    System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
    
                    //msg.To.Add(ToEmailAddress);
                    msg.To.Add("****");
                    msg.From = new System.Net.Mail.MailAddress(""********";");
                    msg.Subject = "Subject";
    
                    msg.IsBodyHtml = true;
                    string EmailBody = " <b>Welcome to Send an Email!!</b><p> Example.<BR>";
                    msg.Body = EmailBody;
                    string smtp = "***";
                    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtp);
                    System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                    NetworkCred.UserName = "********";
                    NetworkCred.Password = "********";
                    NetworkCred.Domain = "********";
                    client.Credentials = NetworkCred;
                    client.Send(msg);
                }
                catch (Exception ex)
                {
    
                    LogError(ex.InnerException.ToString(), ex.StackTrace);
                }
    
    
    
    
    
            }
    
            
        }
    }
    Feature Reciever code below
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    using System.Data.SqlClient;
    namespace TestTimer
    {
        class TestTimerReceiver : SPFeatureReceiver
        {
            const string SYNC_JOB_NAME = "My_Timer_Job";
            public override void FeatureActivated(SPFeatureReceiverProperties properties)
            {
                try
                {
                    SPWebApplication webapp = (SPWebApplication)properties.Feature.Parent;
                    foreach (SPJobDefinition job in webapp.JobDefinitions)
                    {
                        if (job.Name.ToLower()==SYNC_JOB_NAME.ToLower())
                        {
                            job.Delete();
                        }
                    }
    
    
                    TestTimerJob timerJob = new TestTimerJob(SYNC_JOB_NAME, webapp);
                    SPMinuteSchedule schedule = new SPMinuteSchedule();
                    schedule.BeginSecond = 0;
                    schedule.EndSecond = 59;
                    schedule.Interval = 5;
                    timerJob.Schedule = schedule;
                    timerJob.Update();
                }
                catch (Exception ex)
                {
                    
                }
            }
    
            public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
            {
                try
                {
                    SPWebApplication webapp = (SPWebApplication)properties.Feature.Parent;
                    foreach (SPJobDefinition  job in webapp.JobDefinitions)
                    {
                        if (job.Name.ToLower()==SYNC_JOB_NAME.ToLower())
                        {
                            job.Delete();
                        }
                    }
                }
                catch (Exception ex)
                {
                    
                }
            }
    
            public override void FeatureInstalled(SPFeatureReceiverProperties properties)
            {
               
            }
    
            public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
            {
               
            }
        }
    }
    and Feature .xml below
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <Feature  Id="b4fa9cf0-dba9-4206-a37c-e707af6199f9"
              Title="TestTimerReceiver"
              Description="Description for TestTimerReceiver"
              Version="12.0.0.0"
              Hidden="FALSE"
              Scope="Site"
              DefaultResourceFile="core"
              ReceiverAssembly="TestTimer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7f9249145d98c2ad"
              ReceiverClass="TestTimer.TestTimerReceiver"
              
    
              
              xmlns="http://schemas.microsoft.com/sharepoint/">
      <ElementManifests>
        <ElementManifest Location="elements.xml"/>
      </ElementManifests>
    </Feature>

    Comment

    Working...