Sunday, September 20, 2009

Timer Job running on all servers

Scenario:
Lot of people said Custom Timer Jobs are unreliable. But we are using Custom Timer Job for our most of the projects without any issues except one common mistake I have seen developers making is that even though we just want it to run on one machine, it is firing multiple times.

i.e. Custom Timer Job is sending emails more than one time,

Reason:
Most of people start writing Custom Timer Job from AC blog , and it has issues. Infact 2 issues

(1st) Scope = Site which should be Web Application , otherwise users can activate and deactivate it many time in a web application which may not be a good idea.

(2nd) SPJobLockTypes is set to ContentDatabase which may not what you want.

Solution:
After checking the MSDN documentation I found significance of various enumeation values.

ContentDatabase : Locks the content database before processing.
Job : Locks the job to prevent it from running on more than one machine.
None : No locks

So setting the SPJobLockTypes = Job solved the issue. Now timer job runs on one box only. Keep in mind there is no way ( i know of ) to control on which server it is running.

Code:

public SharePointWarmupJob (SPWebApplication webApp)
: base(Globals.JobName, webApp, null, SPJobLockType.Job) {
this.Title = Globals.JobName;
Article:
Similar Entry I found after I posted this :-)

Matt Morse,Robin Meure,Peter Deleu

3 comments:

Robin Meuré September 21, 2009 at 4:42 AM  

Hi mate,

first of all, thanks for the link ;)

Secondly, it is possible to set on which server the timerjob will run by setting the SPServer object in the constructor of the timerjob.

Anonymous,  February 6, 2011 at 9:51 AM  

Thanks for sharing the tips

Anonymous,  March 7, 2012 at 4:48 AM  

Hey, Thanks that's very nice article. Resolved my issue by setting SPJobLockType.Job for Timer job email sending for multiple server.
Thanks. -Keval