Skip to main content

Running Timed Jobs within SharePoint


Programming a Timed Job


The Job installed in the aforementioned paragraph does not actually work because there is no "logic" to execute. To create a new Job, it is necessary to program a new class library and add it to the Global Assembly Cache (GAC) to make the logic accessible to SharePoint.
The first step is to create a new "Class Library" Visual Studio 2005 project with a suitable name, then add a reference to Windows SharePoint Services (Microsoft.SharePoint.dll) and "using" directives to Microsoft.SharePoint and Microsoft.SharePoint.Administration. The Class needs to inherit from "SPJobDefinition" and to have at least one constructor to initialize the new objects. The definition of the empty class reads:
using System;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace CountDocs
{
   public class CountDocsJob : SPJobDefinition
   {
      public CountDocsJob()
      {
      }

      //public CountDocsJob(string MyJobName,
      //SPService MyService,
      //SPServer MyServer, SPJobLockType MyTargetType) :
      //base(MyJobName, MyService, MyServer, MyTargetType)
      //{
      //}

      public CountDocsJob(string MyJobName, SPWebApplication
         MyWebApplication) : base(MyJobName, MyWebApplication,
         null, SPJobLockType.Job)
      {
      }

      public override void Execute(Guid ContentDataBaseID)
      {
      }
   }
}
The base class has two constructors but if two are unnecessary, it is possible to define only one (the second one is commented in the example). The constructor of the sub-classing indicates that the third parameter (the SPServer parameter) is superfluous in this case.

blic override void Execute(Guid ContentDataBaseID)
The functional source code is written in the override "Execute" function. This function always has a parameter that receives the ID of the SharePoint's content DataBase that is executing the Job. For the example, the code reads the number of entries in a List and each time it runs, a new entry is created indicating the time and number of found entries:
{
   try
   {
      SPSite mySite = new SPSite("http://ServerName");
      SPWeb myWeb = mySite.OpenWeb();
      SPList myList = myWeb.Lists["MyJobs"];

      int intCounter = 0;
      foreach (SPListItem myItem in myList.Items)
         intCounter++;

      SPListItem newTask = myList.Items.Add();
      newTask["Title"] = "Counter of Items at " +
         DateTime.Now.ToString();
      newTask["Description"] = "At " + DateTime.Now.ToString() +
         " there are " + intCounter.ToString() +
         " items in the List";
      newTask.Update();
   }
   catch (Exception ex)
   {
      TextWriter myWriter =
         new StreamWriter(@"c:\CountDocsJobError.txt");
      myWriter.WriteLine(ex.ToString());
      myWriter.Close();
   }
}
In the case in point, the code makes a reference to the Site, Web, and List, counts the number of entries in the List, and creates a new entry. The names of the Site and List are fast-coded, but they can be configured in the web.config file of the WebApplication using code similar to this:
Configuration MyConfig =
   WebConfigurationManager.OpenWebConfiguration("/", "Sharepoint -80");
string myValue = myConfig.AppSettings.Settings["MyKeyName"].value;
or extracted from the "ContentDataBaseID" variable.
Sign the assembly with a Safe Name and install it in the GAC (obligatory). After resetting the IIS (iisreset), the previously discussed "CreateJob" routine can be modified to install the Job in the server:
static void CreateJob()
{
   SPServer myServer = SPServer.Local;
   SPSite mySite = new SPSite("http://ServerName");
   SPWebApplication myApplication = mySite.WebApplication;
   SPJobDefinitionCollection myJobsColl =
      myApplication.JobDefinitions;

   CountDocsJob myJob = new CountDocsJob("myCountDocsJob",
      myApplication);
   myJob.Title = "Docs Counter Job";

   SPMinuteSchedule myMinuteSchedule = new SPMinuteSchedule();
   myMinuteSchedule.BeginSecond = 0;
   myMinuteSchedule.EndSecond = 59;
   myMinuteSchedule.Interval = 1;
   myJob.Schedule = myMinuteSchedule;

   myJobsColl.Add(myJob);
   myApplication.Update();

   Console.WriteLine("Job Installed");
}

Comments

Popular posts from this blog

How to deal with SharePoint 2010 exception "An exception occurred when trying to issue security token: The server was unable to process the request due to an internal error"

Scenario: You receive the below exception when you try to logon to a site that has been configured to use Claims Based Authentication with a custom membership provider using FBA credentials: Event ID from Event Log  - 8306 An exception occurred when trying to issue security token: The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.. Explanation: This error started to appear in our QA environment which does not have Visual Studio installed. I have tried starting the service "Claims to Windows Token Service" but that did not help either. I have made sure that all config...

Migrating from Skype for Business to Microsoft Teams: A Step-by-Step Guide

Do you still use Skype for Business to meet the communication and collaboration needs of your business? If so, now is the perfect time to think about switching to Microsoft Teams, a cutting-edge platform with cutting-edge capabilities and seamless connectivity with other Microsoft services. But if you're unfamiliar with the procedure, switching to a new platform can seem like a difficult task. I'll walk you through the process of switching from Skype for Business to Microsoft Teams in this article. Plan the migration in Step 1 You must make a plan before you start the relocation procedure. Set a deadline, make a list of all the Skype for Business capabilities you presently use, and choose whether to migrate gradually or all at once. Step 2: Set up your surroundings. Make sure your network and infrastructure fulfil Microsoft Teams' standards. Upgrades to your hardware, software, and licences might be necessary. Additionally, confirm that you have the right permissions to ca...

Custom Form Base Login Web Part With Sharepoint 2010

In my  Last Post , I talked about creating a Form based authentication web application with Active Directory LDAP. After implementing that you have surely noticed that, when you try to sign in after creating a site collection from FBA web application, you get the following sign in page: Surely, it does not look pretty at all. So, you might want to change this default login page. In order to do this, first let us create an empty SharePoint project in Visual Studio 2010. After that, add an application page by right click-selecting “Add New Item” and you will get like the following window in Solution Explorer: Notice that, when you add any application page to your project, Visual Studio automatically creates a Layouts  folder. To keep things simple enough for your understanding, you may keep your application page under a folder where you might name it as same as your project like the figure above. Now, add a reference for  Microsoft.SharePoint.IdentityModel...