Sander Hogewerf
Sander Hogewerf

Reputation: 33

Azure Web Roles and Instances

I have a web role with multiple instances. I'd like to send an email to my customers with their statistics every morning at 7AM. My problem is the following: if I use a Cron job to do the work mails will be sent multiple times.

How can I configure my instances in order to send only one email to each of my customers?

Upvotes: 1

Views: 99

Answers (2)

Peter Pan
Peter Pan

Reputation: 24148

Per my experience, I think you can try to use a unique instance id to be ensure there is a single instance works for emailing as cron job.

Here is a simple code.

import com.microsoft.windowsazure.serviceruntime.RoleEnvironment;

String instanceId = RoleEnvironment.getCurrentRoleInstance().getId();
if("<instace-id-for-running-cronjob>".equals(instanceId)) {
    // Coding for cron job
    .....
}

As reference, please see the description of the function RoleInstance.getId below.

Returns the ID of this instance.
The returned ID is unique to the application domain of the role's instance. If an instance is terminated and has been configured to restart automatically, the restarted instance will have the same ID as the terminated instance.

More details for using the class above from Azure SDK for Java, please see the list of classes below.

Hope it helps.

Upvotes: 1

Gaurav Mantri
Gaurav Mantri

Reputation: 136334

Typically the way to solve this problem with Multi-instance Cloud Services would be to use Master Election pattern. What you would do is at 7:00 AM (or whenever your CRON job will fire), all your instances will try to acquire lease on a blob. However only one instance will be successful in acquiring the lease while other instances will fail with PreConditionFailed (419) error (make sure you catch this exception!). The instance that acquires the lease is essentially a Master and that instance will send out email.

Obviously the problem with this approach is that what if this Master instance fails to deliver the messages. But I guess that's another question :).

Upvotes: 0

Related Questions