Building a List of All SharePoint Timer Jobs Programmatically in C#

Posted by Damon on Simple Talk See other posts from Simple Talk or by Damon
Published on Tue, 12 Jun 2012 11:56:36 GMT Indexed on 2012/06/12 22:45 UTC
Read the original article Hit count: 189

Filed under:

One of the most frustrating things about SharePoint is that the difficulty in figuring something out is inversely proportional to the simplicity of what you are trying to accomplish.  Case in point, yesterday I wanted to get a list of all the timer jobs in SharePoint.  Having never done this nor having any idea of exactly how to do this right off the top of my head, I inquired to Google.  I like to think my Google-fu is fair to good, so I normally find exactly what I'm looking for in the first hit.  But on the topic of listing all SharePoint timer jobs all it came up with a PowerShell script command (Get-SPTimerJob) and nothing more. Refined search after refined search continued to turn up nothing.

So apparently I am the only person on the planet who needs to get a list of the timer jobs in C#.  In case you are the second person on the planet who needs to do this, the code to do so follows:

SPSecurity.RunWithElevatedPrivileges(() =>
{
   var timerJobs = new List();
   foreach (var job in SPAdministrationWebApplication.Local.JobDefinitions)
   {
      timerJobs.Add(job);
   }
  
foreach (SPService curService in SPFarm.Local.Services)
  
{
      foreach (var job in curService.JobDefinitions)
      {
         timerJobs.Add(job);
      } 
   }
});

For reference, you have the two for loops because the Central Admin web application doesn't end up being in the SPFarm.Local.Services group, so you have to get it manually from the SPAdministrationWebApplication.Local reference.

© Simple Talk or respective owner