Azure Triggered Webjob - Detecting when webjob sto

2019-01-28 04:01发布

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 ?

2条回答
欢心
2楼-- · 2019-01-28 04:13

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

查看更多
混吃等死
3楼-- · 2019-01-28 04:30

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;
    ...
}
查看更多
登录 后发表回答