Pages

Wednesday, October 26, 2011

Sharepoint Timer Job in One Server Only Chosen By You

Ok, this is one scenario that can occur many times! For instance, you have a farm with 4 servers and you want to deploy one Sharepoint Timer Job with site collection scope but you need it to run in an specific server (whatever reasons you have). If you do not indicate what server to run, the installation will install the job in the server that is the admin one (not pretty sure on this one) or, ultimately you will have the same job replicated in every server.

You can see a very good base example how to build an sharepoint timer job here (Andrew Connell Blog), and I will focus this post on how to chose a server to run, not how to install it.

So, to do this, and taking the Andrew Connell's example, you have to do three things:

  • Add a new constructor at SPJobDefinition
  • Get the server you want (SPServer instance)
  • Use the new constructor that implements a different SPJobLockType regarding the example taken

At this time, you are already thinking, "come on!!! some me some code!!!" here it is...

At class that is inheriting the SPJobDefinition you add this constructor
Than, at FeatureActivated method in the TaskLoggerJobInstaller class (the one that inherits from SPFeatureReceiver) you get the server instance you want the job get up and running and use the new constructor added above
























As you can see, you can get the SPServer only by his name (Const.SERVER is a string with server name). But the key here, is the SPJobLockType because you have three choices to use it and to guarantee that it gets register in specific server you chose Job option as you can see in the new constructor. The next image is very self explanatory.













In conclusion, with three simple steps, we can centralize our timer jobs in one specific server making use of the option Job of SPJobLockType and SPServer together. Some warnings... Do not try coding the SPServer with SPJobLockType ContentDatabase, it will fail because you can not do it. On the Execute method, regarding the example, do not use the SPContentDatabase to get the SPSite, use the SPWebApplication, something like this SPSite site = webApplication.Sites[SiteUrl];

References:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spjobdefinition_members.aspx
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spjoblocktype.aspx
http://www.andrewconnell.com/blog/articles/CreatingCustomSharePointTimerJobs.aspx
http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/8a9b9054-ce04-4536-a537-1b2a4f34ca72

No comments:

Post a Comment