Skip to main content

Creating Custom Timer Job in SharePoint 2010

Open Visual Studio 2010 >File > New >Project >SharePoint 2010>Empty SharePoint Project. >Name it Custom_TimerJob>Ok

Check Deploy as farm solution>Finish

create a class that inherits from the Microsoft.SharePoint.Administration.SPJobDefinition class. To implement this class, you need to create a few constructors and override the Execute() method as following
01namespace DotnetFinder
02{
03    class ListTimerJob : SPJobDefinition
04    {
05         public ListTimerJob()
06
07            : base()
08        {
09
10        }
11
12        public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
13
14            : base(jobName, service, server, targetType)
15        {
16
17        }
18
19        public ListTimerJob(string jobName, SPWebApplication webApplication)
20
21            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
22        {
23
24            this.Title = "List Timer Job";
25
26        }
27
28        public override void Execute(Guid contentDbId)
29        {
30
31            // get a reference to the current site collection's content database
32
33            SPWebApplication webApplication = this.Parent as SPWebApplication;
34
35            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
36
37            // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database
38
39            SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];
40
41            // create a new list Item, set the Title to the current day/time, and update the item
42
43            SPListItem newList = Listjob.Items.Add();
44
45            newList["Title"] = DateTime.Now.ToString();
46
47            newList.Update();
48
49        }
50}
51}
As you can see this job just add a new item to a ListTimerJob list every time it’s executed
Now that you have the job built> Right click on the Features >Add Feature

Right click on the Feature1 ” you can rename the Feature1 to any name” > Add Event Receiver

As you can see the event Receiver class inherits from the Microsoft.SharePoint.SPFeatureReceiver and This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade. But we only need FeatureActivated & FeatureDeactivated event handler to install/uninstall our custom timer job as following
01namespace DotnetFinder.Features.Feature1
02{
03[Guid("9a724fdb-e423-4232-9626-0cffc53fb74b")]
04public class Feature1EventReceiver : SPFeatureReceiver
05    {
06        const string List_JOB_NAME = "ListLogger";
07        // Uncomment the method below to handle the event raised after a feature has been activated.
08
09        public override void FeatureActivated(SPFeatureReceiverProperties properties)
10        {
11            SPSite site = properties.Feature.Parent as SPSite;
12
13            // make sure the job isn't already registered
14
15            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
16            {
17
18                if (job.Name == List_JOB_NAME)
19
20                    job.Delete();
21
22            }
23
24            // install the job
25
26            ListTimerJob listLoggerJob = new ListTimerJob(List_JOB_NAME, site.WebApplication);
27
28            SPMinuteSchedule schedule = new SPMinuteSchedule();
29
30            schedule.BeginSecond = 0;
31
32            schedule.EndSecond = 59;
33
34            schedule.Interval = 5;
35
36            listLoggerJob.Schedule = schedule;
37
38            listLoggerJob.Update();
39
40        }
41
42        // Uncomment the method below to handle the event raised before a feature is deactivated.
43
44        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
45        {
46            SPSite site = properties.Feature.Parent as SPSite;
47
48            // delete the job
49
50            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
51            {
52
53                if (job.Name == List_JOB_NAME)
54
55                    job.Delete();
56
57            }
58
59}
60
61   }
Before Deploying you should select the right scope of the Feature in other words in which scope you will activate the Feature(Farm,Site,Web,WebApplication) in our case we will activate Feature1 on Site which is mean Site Collection.

Note : if you trying to activate the feature in the wrong scope will get the following error

Now let us deploy our custom timer job >Right Click on Custom_TimerJob project > Click Deploy

Open now your SharePoint site and select ListTimerJob List and you should see something similar to the following image


Our custom timer job is working fine now you can go and check it and modify the schedule as following
Go to SharePoint 2010 central administration >Monitoring >in the Timer Jobs Section Select Review Job Definitions
and you should See our Custom Timer Job

Click on it and you should see Edit Timer Job Page ,Modify Timer Job schedule based on your requirement
Note : you can also modify schedule of your custom Timer Job from the code but you need to add one of the following class in FeatureActviated Event Handler as following

Comments

Popular posts from this blog

Cascading drop down column in a SharePoint List

This article will show how to use codeplex project to achieve Cascading drop down columns in SharePoint list. This article will show how to achieve parent child relationship in column of SharePoint list.   Objective This article will show how to use codeplex project to achieve Cascading drop down columns in SharePoint list. This article will show how to achieve parent child relationship in column of SharePoint list. Step 1 Download the project from codeplex . Choose WSP file to download. To download the project Click here Step 2 After downloading the WSP add the solution using STSADM command. Navigate to BIN folder and add the solution. Command C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\BIN> stsa dm -o addsolution -filename c:\Stoneshare.CascadingDropDown.WithFilter.wsp Step 3 Open Central ADMIN and deploy solution. Navigate to Operation -> Global Configuration -> Solution Management. Select the Global Deployment option. St...

How to deal with SharePoint 2010 exception "An exception occurred when trying to issue security token: The server was unable to process the request due to an internal error"

Scenario: You receive the below exception when you try to logon to a site that has been configured to use Claims Based Authentication with a custom membership provider using FBA credentials: Event ID from Event Log  - 8306 An exception occurred when trying to issue security token: The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.. Explanation: This error started to appear in our QA environment which does not have Visual Studio installed. I have tried starting the service "Claims to Windows Token Service" but that did not help either. I have made sure that all config...

SharePoint SPFX components basic details and understanding

Microsoft developed SharePoint, a web-based platform that enables businesses and organisations to share and manage documents and information. The SharePoint Framework (SPFx) is a set of client-side tools and components that can be used to construct unique solutions on top of SharePoint. The creation of a SharePoint SPFx component will be covered in this blog. Let's address specific requirements before creating a SharePoint SPFx component. Install the necessary software on your computer: Version 10 or later of Node.js SharePoint Framework (SPFx) generator using Git Now that all the prerequisites have been deployed, let's start developing the SharePoint SPFx component. Start by making a new SPFx project. Making a new SPFx application is the initial step. Launch the command prompt and execute the following commands  yo @microsoft/sharepoint The Yeoman generator for the SharePoint Framework will be started using this command. You will be prompted to enter details about your project...