Custom Timer Job in SharePoint

Introduction:-

This article describes; that how to create custom timer job for SharePoint Server which will cover below points:-

- Timer job basic understanding.
- Creating feature xml
- Creating feature receiver class
- Creating TimerJobdefinition class
- Pass site url to timer job and store timer job property bag without any hard coding

Timer Job Basic:-

Microsoft SharePoint timer jobs perform much of the back-end work that is required to maintain your SharePoint farm. Timer jobs are executable tasks that run on one or more servers at a scheduled time. They can be configured to run exactly one time, or on a recurring schedule like daily, weekly, monthly or Yearly. They are similar to Microsoft SQL Server Agent jobs, which maintain a SQL Server installation by backing up databases, defragmenting database files, and updating database statistics.


Solution Structure:-

Create usual feature receiver project. The package file will look like below image:

timerjob_solution


The Code:-

We will create below feature.xml file, 1 TimerJobFeatureReceiver.cs file and Timer job definition file (CustomJobToPerform.cs). Then rest is usual WSP deployment on sharepoint.

Feature.xml

You use this XML file to define the metadata for the new feature. The following example code scopes the feature at the level of the site and defines a unique identifier for the new feature.

1
2
3
4
5
6
7
8
9
10
11
12
<Feature  Id="place feature guid here"
          Title="MyProject.TimerJob"
          Description="Mu Custom Timer Job"
          Version="12.0.0.0"
          Hidden="false"
          Scope="Site"
          DefaultResourceFile="core"
          xmlns="http://schemas.microsoft.com/sharepoint/"
  	  ReceiverAssembly="MyProject.TimerJob, Version=1.0.0.0, Culture=neutral,
                            PublicKeyToken=312y4373825n8j3a"
          ReceiverClass="MyProject.TimerJob.TimerJobFeatureReceiver" >
</Feature>

TimerJobFeatureReceiver.cs (Feature receiver class)

This class get trigger when we activate feature. This class wll schedule timer job on feature activation as well as will delete time job on feature deactivation. Below is the full class:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Data;
using System.Web;
using System.Web.Configuration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
 
namespace MyProject.TimerJob
{
    public class TimerJobFeatureReceiver : SPFeatureReceiver
    {
        const string JOB_NAME = "CustomMyProjectData";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                using (SPSite site = properties.Feature.Parent as SPSite)
                {
                    // make sure the job isn't already registered
                    foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                    {
                        if (job.Name == JOB_NAME){
                            job.Delete();
                            break;
                        }
                    }
                    // install the job
                    CustomJobToPerform customTimerJob = new CustomJobToPerform
                                (JOB_NAME, site.WebApplication, site.OpenWeb());
                    SPSchedule schedule = SPSchedule.FromString("daily at 04:00");
                    customTimerJob.Schedule = schedule;
                    customTimerJob.Update();
                }
            }
            catch (Exception ex){// Handle Exception
            }
        }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                using (SPSite site = properties.Feature.Parent as SPSite)
                {
                    // delete the job
                    foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                    {
                        if (job.Name == JOB_NAME)
                        {
                            job.Delete();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex){// Handle Exception here
            }
        }
    }
}

CustomJobToPerform.cs (TimerJob definition Class)

The following class “CustomJobToPerform.cs” creates Timerjob class that inherits from SPJobDefinition. This call will get called from feature receiver class. It store site url timer job property bag. That means we need not to hard code the site url. Below is the full code:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Web;
using Microsoft.Office;
using Microsoft.Office.Server;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
 
namespace MyProject.TimerJob
{
    public class CustomJobToPerform : SPJobDefinition
    {
        private string CustomTimerJobUrl = string.Empty;
        #region Constructors
        public CustomJobToPerform()
            : base()
        {
        }
        public CustomJobToPerform(string jobName, SPWebApplication webApp, SPWeb web)
            : base(jobName, webApp, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Custom Timer Job for my projects";
            if (web != null)
            {
                //remove the key if already exist
                bool isKeyExist = this.Properties.ContainsKey(CustomTimerJobUrl);
                if (isKeyExist)
                {
                    this.Properties.Remove(key);
                }
                this.Properties.Add(CustomTimerJobUrl, web.Url);
            }
        }
        #endregion Constructors
 
        public override void Execute(Guid targetInstanceId)
        {
            try
            {
                if (!String.IsNullOrEmpty(this.Properties[CustomTimerJobUrl]))
                {
                    using (SPSite site = new SPSite(this.Properties[CustomTimerJobUrl]))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            // Implement your business requirement here
                        }
                    }
                }
                base.Execute(targetInstanceId);
            }
            catch (Exception ex){// handle exception here
            }
        }
    }
}


Restart timer job service

 
To restart timer job service; go to service (window+run key -> type services.msc > hit enter)
find “Windows SharePoint Services Timer” if you are working for sharepoint 2007
or find “SharePoint 2010 Timer” for sharepoint 2010 and restart it.

You can also use below commands if you are sending batch file to deployment team
For 2007:

net stop “Windows SharePoint Services Timer”
net start “Windows SharePoint Services Timer”

For 2010:

net stop “SharePoint 2010 Timer”
net start “SharePoint 2010 Timer”

Note

1. To debug timer job start timer job service and attach OWSTIMER.exe
2. To deploy timer job send deploy.bat file to deployment team which may content commands like below;-

1
2
stsadm -o activatefeature -fileName MyProject.TimerJob\Feature.xml -url  -force
stsadm -o deactivatefeature -fileName MyProject.TimerJob\Feature.xml -url   -force

Thanks!
Avinash

calendarJune 16, 2012 · cardInfoyen · commentsNo Comments
tagTags: , ,  · Posted in: MOSS, SharePoint

Leave a Reply

Spam Protection: , required

myworldmaps infoyen