27 02 2014
Freebie: Round-Robin SPServer Selector
Here’s a nice little freebie I thought I’d share.
I have a scenario where I have a rather large batch process to run that I’ve decided to split up by creating dozens of timer jobs that process chunks of the batch, and also let me split the the job across all my SharePoint servers! You can pass an SPServer reference into the constructor of SPJobDefinition and as long as you set SPJobLock to Job then the job will only run on that server.
So, I had to build a quick and dirty class that lets me select another application server in my farm each time I call it.
You instantiate it and then each time you call GetNextServer(), you’ll get a new server instance.
1 2 3 4 5 6 7 |
RoundRobinServerChooser serverChooser = new RoundRobinServerChooser(); foreach(var something in someCollection) { SPServer server = serverChooser.GetNextServer(); // ... do something with this new server instance } |
So here’s the full source:
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 |
/// <summary> /// A utility class to get the next server in the farm /// </summary> public class RoundRobinServerChooser { private int currentServerIndex; private List<Guid> serverIds; public RoundRobinServerChooser() { this.serverIds = new List<Guid>(); foreach (SPServer server in SPFarm.Local.Servers) { if ((server.Role == SPServerRole.Application) || (server.Role == SPServerRole.WebFrontEnd)) { this.serverIds.Add(server.Id); } } currentServerIndex = 0; LoggingService.LogVerbose(string.Format("Initialized RoundRobin Server Chooser with {0} servers.", this.serverIds.Count)); } /// <summary> /// Gets the next server. /// </summary> /// <returns> /// The next SharePoint Application Server /// </returns> public SPServer GetNextServer() { if (currentServerIndex == this.serverIds.Count) { currentServerIndex = 0; } Guid currentServerId = this.serverIds[currentServerIndex]; SPServer serverToReturn = SPFarm.Local.Servers[currentServerId]; LoggingService.LogVerbose("RoundRobin Server Chooser: Returning server instance: " + serverToReturn.Name); currentServerIndex++; return serverToReturn; } } |
SharePoint Server Object Model Code in ASP.NET Pages “Unexpected Error” whilst emptying Site Collection Recycle Bin