2

I am trying to get an Az Function to return an HTTP response and continue a background thread after. In the code below I try to use a thread but the response is still waiting for the function to finish before returning. Is there something I am missing?

import logging
import json
import threading
import azure.functions as func
from .commands import start_process


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    command = req.params.get('command')
    vm = req.params.get('vm')

    if not command:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            command = req_body.get('command')
            vm = req_body.get('vm')

    if command == 'restart':

        thread = threading.Thread(target=start_process(vm, command))
        thread.start()

    if command:
    return func.HttpResponse(f"Hello {command}!")
else:
    return func.HttpResponse(
         "Please pass a name on the query string or in the request body",
         status_code=400
    )
Alex D
  • 788
  • 2
  • 11
  • 33

1 Answers1

0

If a program is running Threads (that are not daemon), then the program will wait for those threads to complete before it terminates. Please follow this post for more information.

So, the AZ function (which is a stateless method) that you have created, will wait for the thread to complete as you have attempted to exit from the function by using a return statement. Hence the behavior that you see.

I think you need to look at fire and forget kind of thread execution, and this SO question and answer should help in that.

akg179
  • 1,287
  • 1
  • 6
  • 14