I am adding a simple worker process to an underutilized Azure web role. I have this web role running on 2 instances for reliability/uptime. This worker process was to be set to sleep for around 5 min before performing an action and then sleeping again. By adding this worker process to the web role it will be running on multiple instances and they will both try to perform the same action at the same time. Normally this problem is overcome by using a queue but I don’t need anything nearly that elaborate. I just something to keep the 2 instances from being completely syncronized.
The idea I had was to change the thread.sleep from a hard coded wait time to a random wait time as follows:
Public Overrides Sub Run()
Trace.WriteLine("Worker Role entry point called.", "Information")
While (True)
Dim r As New Random
Dim wait As Integer = r.Next(60000, 600000)
Dim Minutes As Decimal = wait / 60000
Thread.Sleep(wait)
Trace.WriteLine(String.Format("Worker Role - Triggered on {0:f}. Waited {1:N2} Minutes.", Now(), Minutes), "Information")
End While
End Sub
Output from Instance 0:
Information: Worker Role entry point called.
Information: Worker Role – Triggered on Monday, August 27, 2012 9:37 AM. Waited 7.71 Minutes.
Information: Worker Role – Triggered on Monday, August 27, 2012 9:41 AM. Waited 4.25 Minutes.
Information: Worker Role – Triggered on Monday, August 27, 2012 9:49 AM. Waited 7.87 Minutes.
Information: Worker Role – Triggered on Monday, August 27, 2012 9:53 AM. Waited 4.77 Minutes.
Information: Worker Role – Triggered on Monday, August 27, 2012 10:03 AM. Waited 9.91 Minutes.
Output from Instance 1:
Information: Worker Role entry point called.
Information: Worker Role – Triggered on Monday, August 27, 2012 9:38 AM. Waited 9.47 Minutes.
Information: Worker Role – Triggered on Monday, August 27, 2012 9:44 AM. Waited 6.15 Minutes.
Information: Worker Role – Triggered on Monday, August 27, 2012 9:48 AM. Waited 3.41 Minutes.
Information: Worker Role – Triggered on Monday, August 27, 2012 9:49 AM. Waited 1.63 Minutes.
Information: Worker Role – Triggered on Monday, August 27, 2012 9:58 AM. Waited 8.26 Minutes.
Information: Worker Role – Triggered on Monday, August 27, 2012 10:01 AM. Waited 3.14 Minutes.
Does this plan have flaws that I’m not seeing? Thanks for your input!
Well, to answer your titular question, this does nothing to guarantee both of them from doing something at the same time. But it would certainly make that less likely.
That said, using an actual concurrency control mechanism doesn’t have to be “elaborate.” From http://blog.smarx.com/posts/simple-scheduling-in-windows-azure:
Why not just do that? It’s available as a NuGet package, and it shortens your code. 🙂