Search code examples
c#azure-webjobs

Are Azure Web Jobs capable of keeping the task running in background?


I am currently experiencing difficulties with running a long HTTP request in a Web Job. Same application runs fine when started on local machine. Since I've tried multiple ways of trying to make this work I am now curious if this is possible at all.

My testing code below:

        static void Main(string[] args)
        {
            /// [...]Getting configuration and using it in "SendPayload"

            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            Task.Run(async () => { await SendPayloadAndAwait(configuration); });
            while (_isWaiting)
            {
                if (_stopwatch.ElapsedMilliseconds % 5000 == 0)
                {
                    Console.WriteLine(".");
                }
            }
        }

        public static async Task<string> SendPayloadAndAwait (RequestModel targetRequest)
        {
              /// [...]Preparing client and payload 

              Console.WriteLine("Start");
              Response= curClient.SendAsync(req).Result;
              var endContent = Response.Content.ReadAsStringAsync().Result;
              Console.WriteLine("End");

             _isWaiting = false;
             return "Done";
        }

The "End" is never printed in Web Job console, it is an infinite (up to the point of timeout) loop of ".". Is such scenario somehow prohibited?


Solution

  • The way I solved at a previous company was by having the long running job in a Web API which was implemented as an Azure Function was

    • First call (i.e. /api/StartJob)

      • creates a job entry (in azure table)
      • starts backgound thread
      • returns a 202 [Accepted] status with the job entries Id
    • Background thread performs long running task updating job entry with it's progress

    • Client Loop (while percentage done < 100)

      • Requests status (i.e. /api/JobStatus)
        • If percentage done = 100 exit loop

    This was very successful and reliable providing we had a paid for plan

    The free plans kill the session after approx 5 minutes (by design)