Semaphore in Azure Web Job

Viewed 1608

I am wondering if a Semaphore (lock) would work in Azure functions. I do not want two separate webjobs running at the same time. The webjobs live on the same app service plan.

Is this something I can guarantee with a semaphore? (as this enables cross process locking?)

1 Answers

First question: you're talking about Functions and WebJobs. Which one is it?

If your App Service Plan does any scaling, the semaphore will not work since two instances might be started on two different machines. The good thing: (for WebJobs) there's a simple solution for that.

[Singleton]
public static async Task ProcessImage([BlobTrigger("images")] Stream image)
{
     // Process the image
}

In this example, only a single instance of the ProcessImage function will run at any given time. When the function is triggered by a new image being added to the images container, the runtime will first attempt to acquire the lock (blob lease). Once acquired, the lock is held (and the blob lease is renewed) for the duration of the function execution, ensuring no other instances will run. If another function instance is triggered while this function is running it will wait for the lock, periodically polling for it.

You can find more information here: Azure WebJobs SDK - Singleton

Edit:
If you're using Azure Functions: those running based on a TimerTrigger seem to run as Singletons.

The timer trigger supports multi-instance scale-out. A single instance of a particular timer function is run across all instances.

Related