Home > Software design >  How to stop the first function when the second function is called?
How to stop the first function when the second function is called?

Time:11-03

I have called the first "a1" function and it's starts running in the loop and when I called the second "a2" function, the first "a1" function supposed to stop and second function has to start running, but the two functions are running in parallel. I need to stop the first function when the second function is called.

def a1(request):
    if request.method == "POST":
        add = request.POST['addition']
        while True:
            add = add   1
            print(add)
            time.sleep(2)
    return render(request, blog/finished.html)
        
def a2(request):
    if request.method == "POST":
        check = request.POST['checking']
        while True:
            print(check)
            print("second function: ",check)
            time.sleep(2)        
    return render(request, blog/finished.html)

CodePudding user response:

The two requests are running independently hence they cannot communicate with each other directly. You would need to have some means of tracking the state of request a1. In Django, you can do this with a database table which could record the state of a1 (e.g. running). Then a2 can update this state to 'stopped', which a1 would have to poll to find out whether it should stop running or not.

I've ignored why you would want to do this because deliberately putting requests into a loop with sleeps will tie up resources on the webserver and could lead to performance issues.

CodePudding user response:

You should look into Django-channels.

This is a good tutorial and documentation: https://channels.readthedocs.io/en/stable/

This way multiple users/pages can communicate to the same process and receive data from that process without a lot of pain on the webserver.

This uses Redis, so be prepared for that

  • Related