Skip to main content

Creating Custom Timer Job

Timer Job is something which comes into mind when you are looking for batch process in sharepoint.In most of the realtime sharepoint site requires Pulling data from some other application and update the data in sharepoint.In some other scenario we need to synchronize information or Updata date in every day, or give the admin a flexibility execute some batch processing.Its realy good idea to create a Custom Scheduled Job.Let see a Basic skelton code.



using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;


//Class should inherit from  SPJobDefinition

Public class SampleJob : SPJobDefinition


{
       //You could Define Custom properties

        [Persisted()]
        public string MyCustomProperty;

///Implement Following three constructors

public SampleJob (): base(){  }
public SampleJob (string jobName, SPService service, SPServer server, SPJobLockType targetType): base (jobName, service, server, targetType) { }
public SampleJob (string jobName, SPWebApplication webApplication): base (jobName, webApplication, null, SPJobLockType.Job) { }

//You should Override Execute Method

public override void Execute (Guid JobbId) {
//Your Code Execution
//In my case i will be calling a exeternal webservice and synchronize the Data
  }

}


Here basically you will be inheriting  from SPJobDefinition class and then implementing three of the constructors.Then comes main function Execute method , where all of your real excution code goes.You should Override this function to customize the job execution.Another good point you have to watch for the lock type you  specifies in the constructor.


SPJobLockType:

ContentDatabase – this options locks the content database associated with the web application, but the job will be run for each content database associated with the web application.
Job – Ensures that the job will be run only on a single server.
None – Ensures that the Job will be run on all servers.


Next thing how we are going to deploy the Job.Create a feature and and implement FeatureActivated Event and  FeatureDeActivating Event


public class SchedualedJobsFeature : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            SPServer myServer = SPServer.Local;
         
            SPWebApplication myApplication = site.WebApplication;
            SPJobDefinitionCollection myJobsColl = myApplication.JobDefinitions;
            Type sPJobDefinitionType = typeof ( SPJobDefinition);
            
            Type[] types =  typeof  (SchedualedJobsFeature).Assembly.GetTypes ();


            foreach (Type t in types)
            {
                if (t.IsSubclassOf(sPJobDefinitionType))
                {
                    
                    object[] atts= t.GetCustomAttributes ( typeof ( MyJobDefinitionAttribute) , false );
                    if ( atts== null || atts.Length == 0)
                    {
                        continue;
                    }
                    MyJobDefinitionAttribute jobAttribute  = (MyJobDefinitionAttribute) atts[0];


                    SPJobDefinition job = (SPJobDefinition)Activator.CreateInstance(t,
                        jobAttribute  .Title, myApplication, myServer, jobAttribute .LockType );
                    job.Schedule = (SPSchedule) Activator.CreateInstance(jobAtt.ScheduleType);
                    
                    try
                    {
                        SPJobDefinition oldJob = myJobsColl[jobAttribute .Title ];
                        if (oldJob != null)
                        {
                            myJobsColl.Remove(oldJob.Id);
                        }
                        else
                        {
                            
                        }
                    }
                    catch {}


                    try
                    {
                        job.Status = SPObjectStatus.Disabled;
                        myJobsColl.Add(job);


                    }
                    catch (Exception ex)
                    {
                        //Handle Exception
                    }
                    
                }
            }


          }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            SPServer myServer = SPServer.Local;
            SPWebApplication myApplication = site.WebApplication;
            SPJobDefinitionCollection myJobsColl = myApplication.JobDefinitions;


            Type sPJobDefinitionType = typeof(SPJobDefinition);


            Type[] types = typeof(SchedualedJobsFeature).Assembly.GetTypes();




            foreach (Type t in types)
            {
                if (t.IsSubclassOf(sPJobDefinitionType))
                {
                    object[] atts = t.GetCustomAttributes(typeof(MyJobDefinitionAttribute), false);
                    if (atts == null || atts.Length == 0)
                    {
                        continue;
                    }
                    
                    MyJobDefinitionAttribute jobAtt = (MyJobDefinitionAttribute)atts[0];
                    try
                    {
                        SPJobDefinition job = SalesCatalogListItemSync)myApplication.JobDefinitions[jobAtt.Title];
                        myApplication.JobDefinitions.Remove(job.Id);
                    }
                    catch (Exception ex)
                    {
                        //Handle Exeception 
                    }


                }
            }




        }




public class MyJobDefinitionAttribute: Attribute
    {
        public string Title
        {
            get;
            set;
        }
        public Type  ScheduleType
        {
            get;
            set;
        }
        public SPJobLockType LockType
        {
            get;
            set;
        }
    }


Looks simple rite.

Comments

  1. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Oracle training in btm
    Oracle Online Training
    Oracle training in chennai
    Oracle training in Bangalore

    ReplyDelete
  2. Excellent Blog! I would like to thank for the efforts you have made in writing this ExcelR Digital Marketing Classes In Pune post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!

    ReplyDelete

Post a Comment

Popular posts from this blog

How to find Sharepoint DB

In sharepoint world you should know where the sharepoint database is to trouble shoot database related issues.Some one come to you and say i am getting unable to connect to database error or my sharepoint is down.So you may not know the details of the environment.In first step you need to identify the  servers so you have to find the configdb and content db servers. How to find the Config DB Configuration database connection string is stored in Registry key. So sharepoint look for that entry to identify the database. In Sharepoint 2007 you could see the config DB conection string in Following Registry Key My Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\12.0\Secure\ConfigDb In Sharepoint 2010 you could see the config DB conection string in Following Registry Key My Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\Secure\ConfigDb The Next thing you have to find the Content DB attached to Web application.

Ajax Integration with sharepoint

Master Page 1. Add the following tag just below the form tag of master page <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" /> Web.Config 1. Add safe control <SafeControl Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TypeName="*" Safe="True" /> 2. Add the http handler inside <httpHandlers> tag of web.config <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"