Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Triggered Webjob - Detecting when webjob stops

I am developing a triggered webjob that use TimerTrigger.

Before the webjob stops, I need to dispose some objects but I don't know how to trigger the "webjob stop".

Having a NoAutomaticTrigger function, I know that I can use the WebJobsShutdownWatcher class to handle when the webjob is stopping but with a triggered job I need some help...

I had a look at Extensible Triggers and Binders with Azure WebJobs SDK 1.1.0-alpha1.

Is it a good idea to create a custom trigger (StopTrigger) that used the WebJobsShutdownWatcher class to fire action before the webjob stops ?

like image 874
Thomas Avatar asked Feb 02 '16 23:02

Thomas


2 Answers

Ok The answer was in the question :

Yes I can use the WebJobsShutdownWatcher class because it has a Register function that is called when the cancellation token is canceled, in other words when the webjob is stopping.

static void Main()
{
    var cancellationToken = new WebJobsShutdownWatcher().Token;
    cancellationToken.Register(() =>
    {
        Console.Out.WriteLine("Do whatever you want before the webjob is stopped...");
    });

    var host = new JobHost();
    // The following code ensures that the WebJob will be running continuously
    host.RunAndBlock();
}

EDIT (Based on Matthew comment):

If you use Triggered functions, you can add a CancellationToken parameter to your function signatures. The runtime will cancel that token when the host is shutting down automatically, allowing your function to receive the notification.

public static void QueueFunction(
        [QueueTrigger("QueueName")] string message,
        TextWriter log,
        CancellationToken cancellationToken)
{
    ...
    if(cancellationToken.IsCancellationRequested) return;
    ...
}
like image 182
Thomas Avatar answered Oct 31 '22 12:10

Thomas


I was recently trying to figure out how to do this without the WebJobs SDK which contains the WebJobShutdownWatcher, this is what I found out.

What the underlying runtime does (and what the WebJobsShutdownWatcher referenced above checks), is create a local file at the location specified by the environment variable %WEBJOBS_SHUTDOWN_FILE%. If this file exists, it is essentially the runtime's signal to the webjob that it must shutdown within a configurable wait period (default of 5 seconds for continuous jobs, 30 for triggered jobs), otherwise the runtime will kill the job.

The net effect is, if you are not using the Azure WebJobs SDK, which contains the WebJobsShutdownWatcher as described above, you can still achieve graceful shutdown of your Azure Web Job by monitoring for the shutdown file on an interval shorter than the configured wait period.

Additional details, including how to configure the wait period, are described here: https://github.com/projectkudu/kudu/wiki/WebJobs#graceful-shutdown

like image 39
Dusty Avatar answered Oct 31 '22 12:10

Dusty