Search code examples
pythonhtmlflaskcelerypython-asyncio

How can I perform some stuff every 60 seconds in Python Flask, and then update all user pages?


I am currently working on an turn-based online webgame. I want every player to be able to choose a move, and every 60 seconds the chosen moves of all players should get performed simultaneously (if no move is chosen, a default move gets performed). I am planning to save the chosen move in a SQL database. The only problem is, I have no idea, how to perform something each 60 seconds.

I have tried to use asyncio and have read that Celery could help me, but I didn't really understood how to achieve exactly the result I need. As I understood, the guides were helping only to use the stuff inside the flask app, but not simultaneously with the flask app


Solution

  • You can use threading:

    import threading
    import time
    
    def perform_task():
        print("Performing task")
    
    def schedule_task():
        while True:
            perform_task()
            time.sleep(60)
    
    thread = threading.Thread(target=schedule_task)
    thread.start()