0

is there a way to automatically run a function besides my main.py every hour. Using while loop, it does not work, because my main.py is a tkinter class, which after its initialization must not remain "trapped" in a while loop.

This is a initialization part of my main.py:

class ChatApp:
    index = 0

    def __init__(self):
        self.create_index()
        self.window = Tk()
        self._setup_main_window()
        self.start_model()

...

if __name__ == "__main__":
    app = ChatApp()
    app.run()
kaan46
  • 83
  • 6
  • Does this answer your question? [How do you run your own code alongside Tkinter's event loop?](https://stackoverflow.com/questions/459083/how-do-you-run-your-own-code-alongside-tkinters-event-loop) Note that 1 hour = 3600000 milliseconds. – TheLizzard Sep 29 '22 at 10:38
  • Is the code you need to run fast, or doesn't it take more than a few hundred milliseconds to run? There are several ways to accomplish this, but the right one depends on the nature of the code being run. – Bryan Oakley Sep 29 '22 at 14:22

1 Answers1

0

You can run a separate thread which waits an hour between executing. Although it depends on what you want the task to be.

import threading
import time

def func():
   while True:
      #do something
      time.sleep(3600)

t1 = threading.thread(target=func)

class ChatApp:
    index = 0

    def __init__(self):
        self.create_index()
        self.window = Tk()
        self._setup_main_window()
        self.start_model()

...
if __name__ == "__main__":
    t1.start()
    app = ChatApp()
    app.run()
Guy zvi
  • 77
  • 1
  • 6
  • 1
    This should work, but bear in mind that timing using `sleep` isn't terribly precise - I imagine that's not an issue in this particular case, but just FYI. Also, it might be advisable to run the thread as a daemon so it dies when the main process exits, i.e, `t1 = threading.thread(target=func, daemon=True)` – JRiggles Sep 29 '22 at 12:47