Create a Timed Job SharePoint 2007

Sunday, 15 March 2009 13:06 by myro

This post comes from my old website and it's probably outdated. There are other solutions to accomplish a timed job in SharePoint 2007, like using the SharePoint Extensions for Visual Studio. Anyway you can use this post just for a quick reference.

[Outdated]  

Sometimes you have to execute timed tasks using SharePoint 2007, and you need to schedula a job that runs every x minutes. The best way to accomplish this, is to create a SharePoint Feature that installs a SPJobDefinition for your Web Application. In this way, yuo will be able to handler your Timed Job by activating/deactivating your Feature.

Before we create a Feature, we need to develop the Timed Job and the Event Receiver class for our new Feature.
Open a new Project in Visual Studio as a Class Library (myrocode.Feature.TimerJobActivator) and create a class called TimerJob. Here is the code:

 using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace myrocode.Feature.TimerJobActivator
{
  public  class TimerJob : SPJobDefinition
    {
      public TimerJob() : base()
      {
      }
      public TimerJob(string jobName, SPWebApplication webApplication):
          base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
      {
          this.Title = jobName;
      }
        public override string DisplayName
        {
            get
            {
                return "myrocode Timer Job sample";
            }
        }
        public override string TypeName
        {
            get
            {
                return "This Timer Job is just an example";
            }
        }
        public override void Execute(Guid targetInstanceId)
        {
            using (SPWeb currentWeb = new SPSite("http://myro-win2k3:90/").OpenWeb())
            {
                try
                {
                    SPListItem newItem = currentWeb.Lists["Sample List"].Items.Add();
                    newItem["Title"] = "TimerJobWorks - " + DateTime.UtcNow.ToShortTimeString();
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    EventLog EventLog1 = new EventLog();
                    if (!System.Diagnostics.EventLog.SourceExists("WSS timer"))
                        System.Diagnostics.EventLog.CreateEventSource(
                          "WSS timer", "Application");
                    EventLog1.Source = "WSS timer";
                    EventLog1.WriteEntry(ex.Message, EventLogEntryType.Error);
                }
            }
        }
    }
}

The execute method will be called everytime the task needs to be accomplished.
Now let's create an EventReceiver the will activate/deactivate this task:

  •      In your project add a class named Receiver
  •      Paste this code to handler the Feature's activation/deactivation

 
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace myrocode.Feature.TimerJobActivator
{
    public class Receiver : SPFeatureReceiver
    {
        const string JobName = "myrocode timer job";
        const string Listname = "Sample List";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPSite currentSite = (properties.Feature.Parent as SPSite))
            {
                TimerJob myTimerJob = new TimerJob(JobName, currentSite.WebApplication);
                SPMinuteSchedule schedule = new SPMinuteSchedule();
                schedule.BeginSecond = 0;
                schedule.EndSecond = 59;
                schedule.Interval = 1;
                myTimerJob.Schedule = schedule;
                currentSite.WebApplication.JobDefinitions.Add(myTimerJob);
                myTimerJob.Update();
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            using (SPSite currentSite = (properties.Feature.Parent as SPSite))
            {
                foreach (SPJobDefinition job in currentSite.WebApplication.JobDefinitions)
                {
                if (job.Name == JobName)
                    job.Delete();
                }
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
          // throw new Exception("The method or operation is not implemented.");
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
          // throw new Exception("The method or operation is not implemented.");
        }
    }
}


Finally, build your solution giving a strong name and deploy it in GAC (c:\windows\assembly).
What's next? let's create the Feature.xml:

  •      Locate your C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\ folder and create a folder named myrocodeTimerJobActivator
  •      Create a text document called Feature.xml and paste this simple XML 
 <xml version="1.0" encoding="utf-8" />
<Feature Id="84f38120-30a9-11dd-bd11-0800200c9a66"
    Title="myrocode timerjob activator"
    Description="This feature will active your custom timer job"
    Version="1.0.0.0"
    Scope="Site"
    xmlns="http://schemas.microsoft.com/sharepoint/"
    ReceiverAssembly="myrocode.Feature.TimerJobActivator,
                          Version=1.0.0.0,
                          Culture=neutral,
                          PublicKeyToken=9f4da00116c38ec5"

    ReceiverClass="myrocode.Feature.TimerJobActivator.Receiver">
</Feature>

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:  
Categories:   SharePoint 2007
Actions:   Bookmark and Share | Permalink | Comments (2) | Comment RSSRSS comment feed
If you consider this post usefull for your purposes, please consider visiting my sponsors to help me out with the myrocode.com maintenance. Thank you.

Comments