Search This Blog

Thursday, September 18, 2014

Timer Jobs in SharePoint 2010

Overview of Timer Jobs in SharePoint 2010
SharePoint Scheduler Tasks are performing much of the back-end work that is required to maintain your SharePoint Farm. SharePoint Timer jobs are executable tasks that run on one or more servers at a scheduled time, and these scheduled tasks can be configured to run exactly one time, or on a recurring schedule.
What is a Timer Job?
Timer Jobs are recurring background processes that are managed by SharePoint. If you navigate to the Central Administration site, click on the Monitoring link from the main page, and then choose the Review job definitions link under the Timer Jobssection, then you’ll see a list of scheduled timer job instances. A timer job really consists of three parts:- Timer Job Definitions, Timer Job Instances, and Timer Job Schedules.
A timer job definition is a .NET class that inherits from the SPJobDefinition class and defines the execution logic of the Timer Job. Since it is just a .NET class, the Timer Job Definition has all of the things that you would expect a class to have: properties, methods, constructors, etc.
A timer job instance is an object instance of the .NET Timer Job Definition class. You can have multiple instances of a timer job definition, which allows you to define a Timer Job Definition once, but vary the way it operates by specifying different property values for each Timer Job Instance. Whether you need one or many instances of a Timer Job Definition depends entirely on what you are trying to accomplish.
A timer job schedule is the last part. SharePoint exposes a series of pre-defined scheduling classes that derive from the SPSchedule class. A timer job instance must be associated with one of these schedules in order to run, even if you only want to run the timer job instance once

Specifying a Timer Job Lock Type 


Another one of the four key pieces of information that you must provide the timer job instance constructor is the SPJobLockType value which helps dictate where and how many times the timer job runs. There are three options for this value: 
None
Indicates that there are no locks on the job so it will run one time on each server in the farm, but only if the parent web application or service application with which the timer job is associated has been provisioned to that server. If you want a job to run on all the servers in the farm, then this is the option you will want to choose.
ContentDatabase
Indicates that the timer job will run once for each content database associated with the web application with which the timer job is associated. If there is one content database for the web application, it will run once. If there are twenty content databases for the web application, then it will run twenty times. When you specify this option, the targetInstanceId parameter on the Execute method will be populated with the GUID of the content database for which the timer job is firing. Use this option when you have timer job operations that must interact with content databases.
Job
Indicates


SCHEDULING A TIMER JOB INSTANCE

Once you have a job definition, all that is left to do is create an instance of that definition, set any applicable properties on the instance, and associate instance with a schedule that defines how often the timer job runs. To do this, you have to create an appropriate SPSchedule object and assign it to the Schedule property on your timer job instance.
Since the SPSchedule class is an abstract base class that defines common functionality required for scheduling a timer job, you will not be creating instances of an SPSchedule object directly. SharePoint ships with a number of classes that derive from the SPSchedule class that offer a variety of scheduling options. 
Runs the timer job once per year
Runs the timer job once per month on the specified day
   For example, the 15 of the month
Runs the timer job once per month on the specified day and week
   For example, the 3rd Friday of the month
Runs the timer job once per week
Runs the timer job once every day
Runs the timer job once every hour
Runs the timer job once every n minutes
   where n is the value in the 
Interval property
Runs the timer job once


let us start to implement sample Timer job functionality
In this example we are approving the workflow programmatically. For that we need to go

Open Visual Studio 2010 >File > New >Project >SharePoint 2010>Empty SharePoint Project. >Name it Custom_TimerJob>Ok

Check Deploy as farm solution>Finish

From you are Project Solution add new Item(Class file) or create a class that inherits from the Microsoft.SharePoint.Administration.SPJobDefinition class. To implement this class, you need to create a few constructors and override the Execute() method as following…

public class TimerJobFunctionality :SPJobDefinition
    {
        public TimerJobFunctionality()  : base()
        {
            this.Title = "Sample Timer Job Functionality";
        }
        public TimerJobFunctionality(string jobName, SPService service, SPServerserver, SPJobLockType targetType): base(jobName, service, server, targetType)
        {
            this.Title = "Sample Timer Job Functionality";
        }
        public TimerJobFunctionality(string jobName, SPWebApplicationwebApplication) : base(jobName, webApplication, null,SPJobLockType.ContentDatabase)
        {
            this.Title = "Sample Timer Job Functionality";
        }
        public override void Execute(Guid contentDbId)
        {
            SPWebApplication webApplication = this.Parent as SPWebApplication;
// get a reference to the current site collection's content database 
            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
// get a reference to the "site" list in the RootWeb of the first sitecollection in the content database
            string weburl = contentDb.Sites[0].RootWeb.Url;
//Getting the List from the Current All Webs
            SPList timeerJobList = webApplication.Sites[0].AllWebs["/timmerjobs"].Lists["ListName"];
//Getting the SPListItemCollection
            SPListItemCollection itemcollection= timeerJobList.GetItems();
//Iterating the Items Using the Foreach loop
            foreach (SPListItem item in itemcollection)
            {
                   if(timeerJobList.WorkflowAssociations.Count > 0)
                    {
                       if(item.Tasks.Count.Equals(1))
                        {
                           if(String.IsNullOrEmpty(Convert.ToString(item["IsWFSecondLevel"])))
                            {
                                SPWorkflowTask wfTask = item.Tasks[0];
                                Hashtable ht = new Hashtable();
                                ht["Status"] = "Completed";
                                SPWorkflowTask.AlterTask(wfTask, ht, true);   
                            }
                        }   
                   }
            }
        }
   }
As you can see this job just add a new item to a ListTimerJob list every time it’s executed
Now this is time to built the Timer Job> Right click on the Features >Add Feature
Right click on the Feature1 ” you can rename the Feature1 to any name” > Add Event Receiver
As you can see the event Receiver class inherits from theMicrosoft.SharePoint.SPFeatureReceiver and This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade. But we only need FeatureActivated & FeatureDeactivated event handler to install/uninstall our custom timer job as following

        const string timerJonname = "Sample Timer Job Functionality";
        public override void FeatureActivated(SPFeatureReceiverPropertiesproperties)
        {
                SPSite site = properties.Feature.Parent as SPSite;
                site.AllowUnsafeUpdates = true;
                // make sure the job isn't already registered
                foreach (SPJobDefinition job insite.WebApplication.JobDefinitions)
                {
                    if (job.Name.StartsWith(timerJonname,StringComparison.OrdinalIgnoreCase))
                        job.Delete();
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    // install the job
                    TimerJobFunctionality OnTimerJob = newTimerJobFunctionality(timerJonname, site.WebApplication);
                    SPMinuteSchedule schedule = new SPMinuteSchedule();
                    schedule.BeginSecond = 0;
                    schedule.EndSecond = 59;
                    schedule.Interval = 5;
                    OnTimerJob.Schedule = schedule;
                    OnTimerJob.Update(true);
                });
            }
        // Uncomment the method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverPropertiesproperties)
        {
             SPSite site = properties.Feature.Parent as SPSite;
            // delete the job
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name.StartsWith(timerJonname,StringComparison.OrdinalIgnoreCase))
                    job.Delete();
            }
        }


Before Deploying you should select the right scope of the Feature in other words in which scope you will activate the Feature(Farm,Site,Web,WebApplication) in our case we will activate Feature1 on Site which is mean Site Collection.

Now let us deploy our custom timer job >Right Click on Sample_Timer_Job project > Click Deploy

Note:- The above example for Approving the Workflow Programmatically.

No comments:

Post a Comment