【发布时间】:2015-03-28 18:09:57
【问题描述】:
我想要一个服务器和一个检查网络中所有计算机的功能。我想在固定的时间段内定期调用计算机检查功能。所以我想使用“选择”来包含服务器和功能。是否允许将函数作为参数传递给 select 还是只允许将列表传递给 select?
你建议我怎么做才能每 5 秒左右调用一次函数?
【问题讨论】:
标签: python multithreading select server
我想要一个服务器和一个检查网络中所有计算机的功能。我想在固定的时间段内定期调用计算机检查功能。所以我想使用“选择”来包含服务器和功能。是否允许将函数作为参数传递给 select 还是只允许将列表传递给 select?
你建议我怎么做才能每 5 秒左右调用一次函数?
【问题讨论】:
标签: python multithreading select server
尝试实现您自己的线程,每五秒调用一次传递的函数。
from threading import *
import time
def my_function():
print 'Running ...' # replace
class EventSchedule(Thread):
def __init__(self, function):
self.running = False
self.function = function
super(EventSchedule, self).__init__()
def start(self):
self.running = True
super(EventSchedule, self).start()
def run(self):
while self.running:
self.function() # call function
time.sleep(5) # wait 5 secs
def stop(self):
self.running = False
thread = EventSchedule(my_function) # pass function
thread.start() # start thread
【讨论】:
start方法。它现在应该可以工作了。
只需使用threading.Timer
import threading
def check_func():
# other stuff
threading.Timer(5.0, check_func).start() # run check_func after 5s
check_func()
这是在 python 中执行周期性工作的标准方法。
【讨论】: