Check if a SharePoint timer job is currently running

Roy Reznik picture Roy Reznik · Aug 25, 2012 · Viewed 8.8k times · Source

How can I check if a SharePoint timer job is currently running on one of the WFEs ? (Programatically of course).

Answer

Amit Bhagat picture Amit Bhagat · Aug 25, 2012

I have created a console app and tried to put some code but not sure if it fulfills you requirement:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace SPTimerServices
{
    class Program
    {
        static void Main(string[] args)
        {
            const string MY_SERVER = "spsvr";
            var services = SPFarm.Local.Services;

            foreach (SPService service in services)
            {
                if (service is SPWebService)
                {
                    var webService = (SPWebService)service;
                    foreach (SPWebApplication webApp in webService.WebApplications)
                    {
                        foreach (SPJobDefinition job in webApp.JobDefinitions)
                        {
                            // Match with our server
                            if (job.Server != null && string.Compare(job.Server.Address, MY_SERVER, true) == 0)
                            {
                                // Console.WriteLine(job.Name);
                                foreach (var e in job.HistoryEntries)
                                {
                                    if (e.Status == SPRunningJobStatus.Initialized)
                                    {
                                        Console.WriteLine(job.Name);
                                    }
                                }

                            }
                        }
                    }
                }

            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();    
        }
    }
}