Graceful Shutdown Azure WebJobs using SDK functions

When writing Microsoft Azure WebJobs maybe you ask yourself how to detect that the App Service hosting your webjob is shutting down.

Earlier you would do something like this: http://blog.amitapple.com/post/2014/05/webjobs-graceful-shutdown/
As stated there you could create a FileWatcher on the file returned by "Environment.GetEnvironmentVariable("WEBJOBS_SHUTDOWN_FILE")" and then check if file exists. This would indicate that the site is going to stop in X seconds.

But kindly the Azure WebJobs SDK team created a class which does the job for you. It is called WebJobsShutdownWatcher (https://github.com/Azure/azure-webjobs-sdk/blob/master/src/Microsoft.Azure.WebJobs.Host/WebjobsShutdownWatcher.cs).
Now you just need to instantiate this class and use the CancellationToken (.Token) for this task.

Here is a simple example of how you could do this:

static void Main()

{

var config = new JobHostConfiguration();

 

if (config.IsDevelopment)

{

config.UseDevelopmentSettings();

}

 

WebJobsShutdownWatcher watcher = new WebJobsShutdownWatcher();

 

Task.Run(() => {

 

bool isCanceled = false;

 

while (!isCanceled)

{

if (watcher.Token.IsCancellationRequested)

{

// do cleanup/cancel code here

Console.WriteLine("CancellationRequested!");

isCanceled = true;

}

}

}, watcher.Token).Wait();

 

Console.WriteLine("Task cancelled, because of WebJobsShutdownWatcher.Token!");

}

This will result in the following output in the Azure WebJob Logs:

[01/31/2017 16:12:35 > 6daba8: SYS INFO] WebJob is stopping due to website shutting down

[01/31/2017 16:12:35 > 6daba8: SYS INFO] Status changed to Stopping

[01/31/2017 16:12:35 > 6daba8: INFO] CancellationRequested!

[01/31/2017 16:12:35 > 6daba8: INFO] Task cancelled, because of WebJobsShutdownWatcher.Token!

[01/31/2017 16:12:35 > 6daba8: SYS INFO] Status changed to Stopped


Posted Jan 31 2017, 05:32 PM by Holger Vetter
Filed under: ,
developers.de is a .Net Community Blog powered by daenet GmbH.