April 18, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Running Timed Jobs within SharePoint, Page 3

  • August 14, 2007
  • By Gustavo Velez
  • Send Email »
  • More Articles »

First, local variables are created to contain the instance of the local server (type SPServer), the site (type SPSite), and Web application (type SPWebApplication) that will run the Job and the collection of Jobs in the Web application (type SPJobDefinitionCollection).

Then, a new Timed Job is generated using the constructor of SPJobDefinition, together with a name, the reference to the application and server, and one of the type lock elements of the SPJobLockType enumeration ("Job", "ContentDatabase" or "None") as parameters. The new Job in the example is not a proper functioning Job because there is no "logic" behind the source code of the constructor (therefore the name "fake"). After creation, the properties can be set (the Title, in the example).

Subsequent to the formation of the Job, a new schedule variable (type SPDailySchedule in the example, but there are other options such as SPMinuteSchedule, SPHourlySchedule and SPOneTimeSchedule) is prepared, its properties (begin and end time in hours, minutes and seconds) are specified, and the schedule is ascribed to the recently created Job.

Finally, the Job is added to the Jobs Collection and the application is updated. Figure 4 shows the output of a console application running the source code, and the same output on the screen of SharePoint's Central Administration.



Click here for a larger image.

Figure 4: A new Job added

To remove a Job, the "Delete" method of the class SPJobDefinition is used:

static void DeleteJob()
{
   SPSite mySite = new SPSite("http://ServerName");

   foreach (SPJobDefinition oneJob in
            mySite.WebApplication.JobDefinitions)
   {
      if(oneJob.Title == "Fake Test Job")
      {
         oneJob.Delete();

         Console.WriteLine("Job Deleted");
      }
   }
}

An alternate method to eliminate the Job is to locate the ID and delete it from the Job Collection using the "Remove" method from the SPJobDefinitionCollection:

static void DeleteJob2()
{
   Guid myId = new Guid();

   SPSite mySite = new SPSite("http://ServerName");
   SPWebApplication myApplication = mySite.WebApplication;
   SPJobDefinitionCollection myJobsColl =
      myApplication.JobDefinitions;

   foreach (SPJobDefinition oneJob in
            mySite.WebApplication.JobDefinitions)
   {
      if (oneJob.Title == "Fake Test Job")
         myId = oneJob.Id;
   }

   myJobsColl.Remove(myId);
   myApplication.Update();

   Console.WriteLine("Job Deleted");
}




Page 3 of 5



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel