0

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')
Ishaan Masil
  • 65
  • 1
  • 9

1 Answers1

2

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?

swopper
  • 51
  • 4
  • I did see that post earlier, but I didn't really know how to make it work with the threading as I'm quite new to this. Where should I put the `schedule.every().day.at("01:00").do(job,'It is 01:00')` and the while loop? I'd also appreciate if you could tell me what the `time.sleep` is there for since the scheduling is handled by the scheduler – Ishaan Masil Nov 05 '21 at 14:16
  • I've implemented the schedule as per the post you linked, however, the function is not being called (I set it to print a number for every iteration in the for loop and there is no output in the console). Could you take a look? – Ishaan Masil Nov 05 '21 at 14:33
  • The `schedule.run_pending()` method runs all tasks that should be run at that point. The method is fairly simple: https://github.com/dbader/schedule/blob/master/schedule/__init__.py Hence, the `time.sleep` still serves as passing time. – swopper Nov 05 '21 at 14:35
  • I also noticed another post which handles running a scheduler when running an app which explains it very well: https://stackoverflow.com/questions/21214270/how-to-schedule-a-function-to-run-every-hour-on-flask I will add it to the answer. – swopper Nov 05 '21 at 14:36