Azure Function App Graceful Shutdown


Azure Function App Graceful Shutdown


Issue:
·       My function app is about to terminate, how can I notify my function code.
·       My function should not terminate unexpectedly.
·       How to detect host shutdown?
·       When my function app stop/restart then my code should notify and should be able to handle it.

Solution:

You can resolve these types of issue using “Cancellation Token”.

You can specify the CancellationToken parameter which will notify you code whenever function is going to terminate. You can use this notification to make sure the function doesn't terminate unexpectedly in a way that leaves data in an inconsistent state.


Ref:



Example code:

I created one HTTP Trigger function and passed CancellationToken

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Threading;

namespace FunGraceShut
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log, CancellationToken cancellationToken)
        {
            cancellationToken.Register(() =>
            {
                log.LogInformation("Function app is stopping");               

            });
            string name = req.Query["name"];
            if (!cancellationToken.IsCancellationRequested)
            {
                for (int i = 0; i < 100; i++)
                {

                    log.LogInformation("C# HTTP trigger function processed a request.");
                    Thread.Sleep(8000);
                    log.LogInformation("Normal processing for queue message={0}", name);
                }

                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;

                return name != null
                    ? (ActionResult)new OkObjectResult($"Hello, {name}")
                    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
                // the code to process the item goes here
            }
            return name != null
                    ? (ActionResult)new OkObjectResult($"Hello, {name}")
                    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
    }
}



You can refer below image when I stopped it while it was running.


Function App Graceful Shutdown

Ref:




Hope this helps. Please share your feedback.


No comments:

Post a Comment