在程序在给定的时间空闲之后调用函数 [英] call a function after program has been idle for a given time

查看:207
本文介绍了在程序在给定的时间空闲之后调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基于Tkinter的程序需要定期执行一些沉重的维护功能。
由于它是一个连续运行的程序,所以我在考虑在给定的空闲时间后启动这些功能。

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.

你怎么做在Tkinter?我发现关于after_idle在 http://etutorials.org/Programming/Python+tutorial/Part+III+Python+Library+and+Extension+Modules/Chapter+16.+Tkinter+GUIs/16.9+ Tkinter + Events / ,但是当事件循环空闲时,它被调用就是。我需要它来运行我的功能,比如说,在空闲时间的10分钟之后。

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给出了我需要的答案 - 我只是稍微修改如下,以便能够使用 idletime 变量在不同的时间间隔执行不同的任务:

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()


推荐答案

在以下示例中, tick 函数每秒调用一次。 5秒钟后,除非按下键或鼠标按钮1,否则打印消息。

In the following example, the tick function is called every second. After 5 seconds, a message is printed, unless a key or mouse button 1 were pressed.

import time
from Tkinter import *

root = Tk()
running = None

def reset(*ignore): 
    global running
    running = None

def tick(*ignore):
    global running
    if not running:
        running = time.time()
    elif time.time() - running > 5:
        print 'I waited 5 seconds...'
        running = None
    root.after(1000, tick)   

root.after(1000, tick)    
root.bind('<Key>', reset)
root.bind('<Button-1>', reset)
root.mainloop()

这篇关于在程序在给定的时间空闲之后调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆