My Tkinter-based program needs to periodically perform some “heavy” maintenance functions.
Since it is a program that is running continuously, I was thinking of launching those functions only after a given amount of idle time.
How do you do it in Tkinter? I found about about after_idle in http://etutorials.org/Programming/Python+tutorial/Part+III+Python+Library+and+Extension+Modules/Chapter+16.+Tkinter+GUIs/16.9+Tkinter+Events/, but that gets called just when the event loop is idle. I need it to run my functions, say, after 10 minutes of idle time instead.
~~~
Mr.Steak gave the answer I needed – I just modified it slightly as follows to be able to perform different tasks at different intervals, using the idletime variable :
import time
from Tkinter import *
root = Tk()
def resetidle(*ignore):
global idletime
for k in idletime: k['tlast']=None
def tick(*ignore):
global idletime
t=time.time() # the time in seconds since the epoch as a floating point number
for k in idletime:
if not k['tlast']:
k['tlast'] = t
else:
if t-k['tlast']>k['tmax']:
k['proc']()
k['tlast'] = None
root.after(5000, tick) # reset the checks every 5''
idletime=[{'tlast':None,'tmax':60,'proc':test1}, # every 1'
{'tlast':None,'tmax':3600,'proc':test2}] # every 1h
root.after(5000, tick)
root.bind('<Key>', reset)
root.bind('<Button-1>', reset)
root.mainloop()
In the following example, the
tickfunction is called every second. After 5 seconds, a message is printed, unless a key or mouse button 1 were pressed.