python - 时间特定线程

标签 python linux multithreading dictionary

我正在编写一个程序,它有一个带有时间(以及其他信息)的字典,但关键是我需要为每个条目创建一个单独的线程,当线程运行时,执行一个简单的一行命令然后 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/

相关文章:

安卓 "Only the original thread that created a view hierarchy can touch its views."

java - 连续暂停/停止和启动/恢复Java TimerTask?

java - 将线程与 Google Places API 结合使用

python - Docker - "127.0.0.1"不是有效端口 - Django

python - 处理本地文件和更新 Titan 图数据库的最佳方式

c - 只有一次 write() 调用通过套接字连接发送数据

linux - 当唯一的访问是通过 FTP 时,如何终止 Linux 进程?

python - binarySearch 与 in,意外结果 (Python)

python - 解码 SEGD 文件并绘制其中的任何轨迹

javascript - 如何从 df ~ 提取数据到我的网站?