我正在编写一个程序,它有一个带有时间(以及其他信息)的字典,但关键是我需要为每个条目创建一个单独的线程,当线程运行时,执行一个简单的一行命令然后 sleep 指定的时间(从字典中传递)然后重新运行。这是我要实现的目标的示例:
#!/usr/bin/python
import threading
import time
class worker(threading.Thread):
def __init__(self,timer):
while True:
print("job %s" % timer)
time.sleep(timer/100)
if __name__ == "__main__":
mydict = {1:150, 2:250, 3:350}
for values in mydict.keys():
new_worker_thread = worker(values)
字典中的每个值代表一个时间(以毫秒为单位),这需要传递给线程然后运行直到停止。
如有任何帮助,我们将不胜感激。
谢谢 吉姆
编辑
抱歉,这可能还不清楚。
我正在使用的 for 循环似乎只为字典中的第一个值创建了一个线程。我在让所有线程以正确的时间运行时遇到问题
最佳答案
这给了你预期的输出(我想,如果我错了请纠正我):
class worker(threading.Thread):
def __init__(self, timer):
self.timer = timer
super(worker, self).__init__()
def run(self):
while True:
print("job %s" % self.timer)
time.sleep(10)
if __name__ == "__main__":
mydict = {1:150, 2:250, 3:350}
for values in mydict.keys():
print(values)
new_worker_thread = worker(values)
new_worker_thread.start()
关于python - 时间特定线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30375817/