65.9K
CodeProject is changing. Read more.
Home

Exiting an Azure WebJob programmatically

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Sep 28, 2023

CPOL
viewsIcon

5710

Shows how to programmatically stop/exit a WebJob on Azure

Introduction

If you need your WebJob to run a task and exit, or if you need to conditionally exit it under certain scenarios, and you thought it’s just a matter of exiting the worker service’s ExecuteAsync method, you’d be wrong. Even after your worker code has stopped running, the parent host stays alive. The right way to exit your WebJob is to inject IHostApplicationLifetime into your worker, and then the last line of code in your ExecuteAsync would be a call to its StopApplication method.

Example code

public Worker(ILogger<Worker> logger, IHostApplicationLifetime appLifeTime)
{
    _logger = logger;
    _appLifetime = appLifeTime;            
}
 
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    int runs = 0;
 
    while (!stoppingToken.IsCancellationRequested && runs++ < 3)
    {
        // do some task here   
        await Task.Delay(2000, stoppingToken);
    }
 
    _appLifetime.StopApplication();
}

References