大家好我是Python的新手,我无法找到适用于我的方案的任何方法。如何使用不同的参数启动相同功能的多个重复性任务,并且仍然能够停止某个任务?
为了让事情更清楚,请检查下面的图像。我有一个f(x)函数。我想启动多个独立的重复呼叫,使用不同的条目数据,以后再单独停止它们。
description http://happyfacedevs.com/public/python.png
更新:这是整个方案。我有一个主要功能,每60秒调用一次。此函数获取网址列表,并根据某些条件决定使用给定网址启动重复功能或停止已经运行的网址。
def f(x):
#repeat every 5 secs until stopped
#do stuff with x
def mainTask():
#gets a new list of urls
#for every url, start a new repeating task or stop an existing one
#based on some conditions
threading.Timer(60, mainTask).start()
mainTask()
答案 0 :(得分:2)
您可以使用gevent.spawn()来实现您的独立任务。来自http://www.gevent.org/intro.html#example
的摘录>>>import gevent
>>>from gevent import socket
>>>urls = ['www.google.com', 'www.example.com', 'www.python.org']
>>>jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]
>>>gevent.joinall(jobs, timeout=2)
>>>[job.value for job in jobs]
['74.125.79.106', '208.77.188.166', '82.94.164.162']
答案 1 :(得分:0)
如果a,b,c
始终保持不变:
import time
import threading
def f(param, stop_event):
while not stop_event.is_set():
# do something with param
events = {'a': threading.Event(),
'b': threading.Event(),
'c': threading.Event(),
}
for param, ev in zip([a, b, c], events):
t = Thread(target=f, args=(param, ev))
t.start()
time.sleep(10)
events['a'].set() # stop a
time.sleep(10)
events['b'].set() # stop b
time.sleep(10)
events['c'].set() # stop c
如果迭代中有a,b,c
个新内容,您可以使用Queue
:
import time
import threading
def f(q, stop_event):
while not stop_event.is_set():
param = q.get()
# do something with param
q = threading.Queue()
events = {'a': threading.Event(),
'b': threading.Event(),
'c': threading.Event(),
}
for ev in events:
t = Thread(target=f, args=(q, ev))
t.start()
q.put(a)
q.put(b)
q.put(c)
time.sleep(10)
events['a'].set() # stop a
time.sleep(10)
events['b'].set() # stop b
time.sleep(10)
events['c'].set() # stop c
这是一些示例解决方案。
答案 2 :(得分:0)