代码之家  ›  专栏  ›  技术社区  ›  mouche

每X分钟运行一次函数-Python

  •  12
  • mouche  · 技术社区  · 16 年前

    我正在使用Python和PyGTK。我对运行某个函数感兴趣,该函数每隔几分钟从串行端口获取数据并保存。

    目前,我正在使用时间库中的sleep()函数。为了能够进行处理,我的系统设置如下:

    import time
    waittime = 300 # 5 minutes
    while(1):
        time1 = time.time()
        readserial() # Read data from serial port
        processing() # Do stuff with serial data, including dumping it to a file
        time2 = time.time()
        processingtime = time2 - time1
        sleeptime = waittime - processingtime
        time.sleep(sleeptime)
    

    此设置允许我从串行端口读取数据之间有5分钟的间隔。我的问题是,我希望我的readserial()函数能够每5分钟暂停一次正在发生的事情,并且能够一直做事情,而不是使用time.sleep()函数。

    谢谢

    4 回复  |  直到 16 年前
        1
  •  23
  •   Anurag Uniyal    14 年前

    不要在睡眠时使用这样的循环,它会阻止gtk处理任何UI事件,而是使用gtk定时器,例如。

    def my_timer(*args):
        return True# do ur work here, but not for long
    
    gtk.timeout_add(60*1000, my_timer) # call every min
    
        2
  •  9
  •   Community Mohan Dere    8 年前

    这正像 my answer here

    如果时间不是精确到十分之一秒的关键时间,请使用

    glib.timeout_add_seconds(60, ..)
    

    否则如上所述。

    超时\u添加\u秒 允许系统将超时与其他事件对齐,从长远来看,减少CPU唤醒(特别是在超时重新发生时)和 save energy for the planet (!)

        3
  •  5
  •   wwwilliam    15 年前

    gtk.timeout\u add似乎已被弃用,因此您应该使用

    def my_timer(*args):
        # Do your work here
        return True
    
    gobject.timeout_add( 60*1000, my_timer )
    
        4
  •  0
  •   Leon    13 年前

    import wx
    wx.CallLater(1000, my_timer)