Search code examples
azure-webjobs

Can I run some code in a WebJob after the timeout has been reached?


I have a continuos WebJob using the ServiceBusTrigger. I also set a timeout of 10 minutes. If the function finishes before, it sends a response to another queue.

But in case of a timeout, it just exits. Is it possible to run some code when timeout is reached? Like a callback function. So I can send a proper message that the process timed out.

    [Timeout("00:10:00")]
    public static async Task ProcessPreflightQueueMessage([ServiceBusTrigger("%preflightQueue%")] string message, CancellationToken token, ILogger logger)
    { ... }

Solution

  • Yes you could, while the function timeout, it will throw TaskCanceledException, you could catch it and do your stuff.

    Here is my test.

    public class Functions
    {
        [Timeout("00:00:30")]
        public static async Task TimeoutJob(
            [QueueTrigger("myqueue")] string message,
            CancellationToken token,
            TextWriter log)
        {
    
            try
            {
                await log.WriteLineAsync(message);
                log.WriteLine($"-- [{DateTime.Now.ToString()}] Processing Begin --");
                await Task.Delay(TimeSpan.FromMinutes(1), token);
                log.WriteLine($"-- [{DateTime.Now.ToString()}] Complete Time-consuming jobs --");
            }
            catch (TaskCanceledException)
            {
                log.WriteLine("timeout");
            }
            log.WriteLine($"-- [{DateTime.Now.ToString()}] Processing End -- ");
        }
    
    }
    

    enter image description here