Sunday, February 17, 2013

Code trick to manipulate existing SPtimer jobs

Today I got to go on a trip down memory lane.

Long story short I had to create a sp2007 timerjob, had a few ups and downs and found this very helpful post to manipulate already running timer jobs.

SharePoint 2007 has a number of timer jobs. These are things that run on a scheduled basis.
To see a list of them go to Central Administration > Operations > Timer Job Definitions

So say for instance, Contoso wants you to deliver a solution based on "Information Management Policy" in a flat 4 hours. Well that's great, except that you can't demo it because guess what, that job is set to run on a daily basis. I think it would be very useful to test such things that run based on a timer in a development environment, so there has to be a way to configure these jobs to run on a shorter time schedule. Luckily, there is such a way.

For instance, the "Information Management Policy" job, is a part of the "PolicyConfigService" One way would be to use SharePoint's API to write code to change the job's schedule.

namespace ConsoleApplication1
{
    using System;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;

    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite tmpSPSite = new SPSite("http://moss2007"))
            {
                SPServiceCollection tmpSPServiceCollection = tmpSPSite.WebApplication.Farm.Services;

                foreach (SPService tmpSPService in tmpSPServiceCollection)
                {
                    if (tmpSPService.Name == "PolicyConfigService")
                    {
                        foreach (SPJobDefinition tmpSPJobDefinition in tmpSPService.JobDefinitions)
                        {
                            if (tmpSPJobDefinition.Title == "Information management policy")
                            {
                                SPMinuteSchedule tmpSchedule = new SPMinuteSchedule();
                                tmpSchedule.BeginSecond = 0;
                                tmpSchedule.EndSecond = 59;
                                tmpSchedule.Interval = 5;

                                tmpSPJobDefinition.Schedule = tmpSchedule;
                                tmpSPJobDefinition.Update();
                            }

                            Console.WriteLine("JOB: " + tmpSPJobDefinition.Title);
                        }
                    }
                }
            }
        }
    }
}

As you can see, the above code replaced the schedule for the Information management policy job to a minute based schedule.

Now, when you set a site collection policy to delete a document, it can be demonstrated in a minute's time.

No comments:

Post a Comment