Azure Triggered Webjob - Detecting when webjob stops

前端 未结 2 2015
梦如初夏
梦如初夏 2020-12-11 05:30

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\

相关标签:
2条回答
  • 2020-12-11 05:57

    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;
        ...
    }
    
    0 讨论(0)
  • 2020-12-11 06:08

    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

    0 讨论(0)
提交回复
热议问题