Create Custom SharePoint Timer Job

In this article, I would like to show you on steps to create Custom SharePoint Timer Job in SharePoint 2010.

Below is step by step guide to implement Custom SharePoint Timer Job:

  1. Start your Visual Studio 2010 > File > Project > Empty SharePoint Project, Enter project name and  location. Click OK.
    timer1
  2. In SharePoint Customization Wizard, Select Deploy as farm solution. Click Finish.
    timer2
  3. Right click on the project and select Add New Item and Enter Class Name to MyTimerJob.
  4. Inherits MyTimerJob class from SPJobDefinition class and override Execute method.
    using System;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    
    namespace TimerJobProject
    {
        class MyTimerJob : SPJobDefinition
        {
            public MyTimerJob() : base()
            {
            }
    
            public MyTimerJob(string sJobName, SPService service, SPServer server, SPJobLockType targetType) : base(sJobName, service, server, targetType)
            {
            }
    
            public MyTimerJob(string sJobName, SPWebApplication webApplication) : base(sJobName, webApplication, null, SPJobLockType.ContentDatabase)
            {
                this.Title = "My Custom Timer Job";
            }
    
            public override void Execute(Guid contentDbId)
            {
                // Get the current site collection's content database
                SPWebApplication webApplication = this.Parent as SPWebApplication;
                SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
    
                // Get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database
                SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];
    
                // Add a new list Item
                SPListItem newList = Listjob.Items.Add();
                newList["Title"] = DateTime.Now.ToString();
                newList.Update();
            }
        }
    }
    
  5. Add Feature to install and delete MyTimerJob. Set Feature Scope to Site scope.timer3
  6. Add Event Receiver to Override Feature Activated and Feature Deactivating methods.
    timer4

    using System;
    using System.Runtime.InteropServices;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    
    namespace TimerJobProject.Features.MyTimerJobFeature
    {
        /// <summary>
        /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
        /// </summary>
        /// <remarks>
        /// The GUID attached to this class may be used during packaging and should not be modified.
        /// </remarks>
    
        [Guid("a35939eb-23a2-4d0e-8437-19526c9c04c6")]
        public class MyTimerJobFeatureEventReceiver : SPFeatureReceiver
        {
            const string List_JOB_NAME = "ListLogger";
    
            // Uncomment the method below to handle the event raised after a feature has been activated.
            public override void FeatureActivated(SPFeatureReceiverProperties properties)
            {
                SPSite site = properties.Feature.Parent as SPSite;
    
                // Delete the job if already registered
                foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                {
                    if (job.Name == List_JOB_NAME)
                        job.Delete();
                }
    
                // Install the timer job
                MyTimerJob listLoggerJob = new MyTimerJob(List_JOB_NAME, site.WebApplication);
                SPMinuteSchedule schedule = new SPMinuteSchedule();
                schedule.BeginSecond = 0;
                schedule.EndSecond = 59;
                schedule.Interval = 5;
                listLoggerJob.Schedule = schedule;
                listLoggerJob.Update();
            }
    
            // Uncomment the method below to handle the event raised before a feature is 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 == List_JOB_NAME)
                        job.Delete();
                }
            }
    
            // Uncomment the method below to handle the event raised after a feature has been installed.
            //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
            //{
            //}
    
            // Uncomment the method below to handle the event raised before a feature is uninstalled.
            //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
            //{
            //}
    
            // Uncomment the method below to handle the event raised when a feature is upgrading.
            //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
            //{
            //}
        }
    }
    
  7. Build and Deploy Solution.
  8. Go to SharePoint Central Administration site > Monitoring > Review job definitions, you could see your Custom Timer Job there.timer5
    timer6

Now its time to Test it.

  1. Go and grab cup of coffee before you check your work.
  2. Go to SharePoint site > Site Actions > View All Site Content > Look for ListTimerJob list.
  3. Few items should be populated after more than 5 minutes and new item will be added every 5 minutes.timer7

Debug your solution.

  1. Attach your solution to process OWSTIMER.
    timer8
  2. Put a break point inside your Execute method in the MyTimerJob class.
    timer9
  3. Wait until it hits the break point.
Advertisements

Tagged: ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: