Search This Blog

Wednesday, March 23, 2016

Creating SharePoint Timer Job

Timer Job:

Timer Job is a background process that are run by SharePoint. It is a periodically executed task inside SharePoint Server. It provides us a task execution environment.


Default Timer Jobs inside SharePoint:

There are many timer jobs inside SharePoint which do internal tasks like:
    • Send emails
    • Validate sites
    • Delete unused sites
    • Health analysis
    • Product versioning
    • Diagnostics
These tasks will having execution periods like:
    • Minute
    • Hour
    • Day
    • Week
    • Month

1) Create an empty SharePoint project and add an class file in that project.
    Derive CustomTimerJob Class from SPJobDefinition which comes from 
    Microsoft.SharePoint.Administration.dll

Example:
    class TestTimerJob : SPJobDefinition
    {
     }

2) Add the three Constructors of the derived class : When ever we create the object of CustomTimerJob  class, corresponding constructor will execute.
   
Example:  
  public TestTimerJob() : base()
        {
        }

   public TestTimerJob(string sJobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(sJobName, service, server, targetType)
        {
        }

   public TestTimerJob (string sJobName, SPWebApplication webApplication)
            : base(sJobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Test Time Job";
        }

3) Override the Execute method: When ever the timer job start running then the code inside the Execute method will run.

Example: 


public override void Execute(Guid targetInstanceId)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite Osite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb Oweb = Osite.OpenWeb())
                        {
                            SPList TestTasksList = Oweb.Lists.TryGetList("TestTasksList ");                          
                            SPListItemCollection TestTasksListCol = TestTasksList.GetItems();
                            foreach(SPListItem Oitem in TestTasksListCol)
                           {       
                                 Oitem["Title"]="TimerJob";
                                  Oitem.Update();   
                           }
                        }
                    }
                });
            }
            catch (Exception)
            {
                throw;
            }
        }


4) We need to create a Feature and Feature Receiver so on activation of this feature we are going the add our timer job to SharePoint farm.
    1. Create a new feature and set its scope as Site
    2. Add an event receiver by right clicking that feature. 
    3. And also create a name for your timer job;

const string JOB_NAME = "Test TimerJob";

       In that feature include the following code for Feature activated and Feature Deactivating

Feature Activated:
 public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == JOB_NAME)
                    job.Delete();
            }
            OverdueTasksTimerJob listLoggerJob = new OverdueTasksTimerJob(JOB_NAME, site.WebApplication);
            //SPMinuteSchedule schedule = new SPMinuteSchedule();
            SPDailySchedule schedule = new SPDailySchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            //schedule.Interval = 5;
            listLoggerJob.Schedule = schedule;
            listLoggerJob.Update();
        }

Feature Deactivated:
       public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            // Delete the timer job
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == JOB_NAME)
                    job.Delete();
            }
        }

5) Next deploy you solution and check you timer job is comes under Job definitions in Monitoring option in central admin. If it doesn't come then activate the feature manually using Power shell command.

Example:
Enable-SPFeature FeatureFolderName -Url http://server/site/subsite

Note: you can get the Feature name from the following path:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\FEATURES


    
   
























No comments:

Post a Comment

Restricting Custom People Picker to only one Sharepoint group programatically

Refer the following script files in your page,     <!-- For People Picker -->     <script type="text/javascript" src...