Monday 1 April 2013

Creating Custom Timer Job in share point 2010



Creating  Custom  Timer Jobs  in Share point 2010



A Timer job is periodically executed task on the share point server. Timer job is object of a class which is derived from  SPJobDefinition

A timer job can be described in three parts  :  Job DefinitionsJob Instances, and  Job Schedules.
Timer job definition is a .net class that is inherited from SPJobDefinition.  JobInstance , as the name suggests is instance of job definition which allows us to create multiple Instances of the same job with different properities. These job instances are scheduled for to run on some Web Application (SPWebApplication) or some Service (SPService) or on Server (SPServer). For ex Minutes , Daily, Weekly. Etc.
 From Central Administration >>Monitoring >> Review Job Definition , we can see various jobs which are scheduled . jobs running , history etc.

Timer Job Association


A timer job instance must be associated with either a SharePoint web application (SPWebApplication) or a SharePoint service application (SPService). It may also be associated with a server (SPServer) if you desire, but it is not a requirement. The reason behind the association requirements is that the SPJobDefinition class inherits from the SPPersistedObject class.
There are 3 constructors of SPJobDefinition .one Is default,  One of the constructors allows you to associate the timer job with a web application, and the other allows you to associate it with a service application.
For to associate a timer job to Central Admin just Pass SPWebAdministration.Local  as webApplecation. We can not associate a timerjob with a server and skipping other entities.
One other thing we must have some association . we can not pass null to association.
It is enough Lets start creating a Timer Job.

Creating  Custom Timer Job


Lets Start Step By Step . create a empty share point project  in the name box type TimerJobProject.
Right click on the project >> Add new Item  . add a class  name it TimeJob.cs , by default I will show as bellow.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Data;
using System.IO;

namespace TimerJob
{
    class TimeJob
    {
    }
}

Inherit this class with SPJobDefinition. For this add using statements.
using Microsoft.SharePoint.Administration;

class TimeJob : SPJobDefinition

now I will associate this timer job with WebApplecation so add constructor.
      
       /*DEFAULT CONSTRUTOR WITHOUT PUBLIC DEFAULT CONSTRUCTURE JOB CAN NOT BE DESERIALISED */
public TimeJob()
            : base()
        {
            this.Title = "Custom Timer Job";
        }
 public TimeJob(SPWebApplication webApplication) /* PASS TO BASE CLASS base( name,webapplecation,server,locktype*/
            : base("Custom Timer Job", webApplication, null, SPJobLockType.Job)
        {
            Title = "Project Status Timer Job";
        }

Now it is time to write some custom code I will send email simply. Override Execute method of SPJobDefinition.

public override void Execute(Guid targetInstanceId)
        {
          
          
            try
            {
                SPWebApplication webapp = this.Parent as SPWebApplication;
                SPSite site = webapp.Sites[0];

                SPWeb web = site.RootWeb;
             
               /*USE NAME SPACE USING SHAREPOINT.UTILITIES*/
               SPUtility.SendMail(web,"your email id ", "TimeJobEmail", “TestEmail”);
            }
            catch (Exception ex)
            {
               
               
               
            }
        }
OK Our Custom timer job has been created now need create and delete this timer job. So add a feature if not already added and add feature receiver.

Don’t forget to give scope of this feature to site.

Now on feature activated create and schedule timer job as bellow first delete job as during testing we usually deploy many times .

SPSite site = properties.Feature.Parent as SPSite;
            DeleteJob(site);// will be write this method to delete job
            TimeJob tasksTimerJob = new TimeJob(site.WebApplication);
       

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 1;
            tasksTimerJob.Schedule = schedule;
            tasksTimerJob.Update();


avobe code creates and schedules job to run every minutes. For deleting job iterate for every job in webapplecation and find the job and delete it

private void DeleteJob(SPSite site)
        {
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name.Equals(“Custom Timer Job”,
                StringComparison.OrdinalIgnoreCase))
                {
                    job.Delete();
                }
            }
        }
Now on feature deactivativating delete the job simply.
       public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            DeleteJob(site);
        }
Deploy the Project Go to Central Admin>> Monitoring>> Review timer job. you will have your Timer job. You can schedule it

Once you have deployed the timer job it may not updated . on run type services.msc it will open services. Search for Share point 2010 Timer Services and restart it.

It at some place it need to debug the job then Please remember it can not be debugged by w3wp.exe as it is iis worker process.

Attach OSTIMER.EXE  to from debug >> attach process and run timer job to debug the job.











Setup dev environment for spfx

So lets setup dev environment for SharePoint Framework abbreviated as SPFX. for an Introduction of What is SPFX and What are the capebiliti...