Search code examples
pythonflaskscheduled-taskspython-multithreading

How do I call a function every 24 hours in Python? I'm currently using Threading to run a Flask server and the function at the same time


Right now, I'm trying to make a graphing website that tracks the progress (XP) of Discord users with a bot called MEE6, here is my repl. Right now, I'm using Threading to create two separate threads - one for a web server, and one containing a while loop with the function inside:

def func():
    while True:
        backend.get_details()
        time.sleep(86400)

This should make the function run every 24 hours, but as evidenced by the time stamps in the database:

  "05-November-2021 00:02:58": 2106855,
  "05-November-2021 00:52:48": 2106855,
  "05-November-2021 01:23:21": 2106855,
  "05-November-2021 03:48:13": 2106874,
  "05-November-2021 07:13:40": 2106874

It is not. How can I fix this?

Here is my threading code:

def keep_alive():
server = Thread(target=run)
data = Thread(target=func)
server.start()
data.start()

def run():
    app.run(host="0.0.0.0", port=8000)

if __name__ == '__main__':
    # s.run()
    # os.system('cls')
    keep_alive()
    # print('i')

Solution

  • Have you tried fixing it using the schedule package? For an example see this post:

    Python script to do something at the same time every day

    For running a scheduler in the background (i.e. while running an app) see this excellent post:

    How to schedule a function to run every hour on Flask?