为什么计时器不会在多进程中的线程中工作?

时间:2018-07-23 18:38:42

标签: python timer process python-multiprocessing python-multithreading

我正在尝试在Process的{​​{1}}中运行代码。该代码使用multiprocessing中的Timer。计时器似乎永远不会启动。为什么是这样?我可以使用以下代码重现该问题,该代码只打印一次时间。

threading

输出: from multiprocessing import Process from threading import Timer import time def print_time_every_5_seconds(): Timer(5,print_time_every_5_seconds).start() print(time.ctime()) start_process = Process(target=print_time_every_5_seconds) start_process.start()

1 个答案:

答案 0 :(得分:1)

问题是您的ProcessTimer事件触发之前结束。如果您可以使Process保持活跃,那么它将起作用。这是一种方法:

from multiprocessing import Process, SimpleQueue
from threading import Timer
import time
import functools

def print_time_every_5_seconds(que):
    while True:
        print(time.ctime())
        t = Timer(5,functools.partial(que.put, (None,))).start()
        que.get()



if __name__ == '__main__':
    que = SimpleQueue()
    start_process = Process(target=print_time_every_5_seconds, args=(que,))
    start_process.start()

另一种实现方法是将start方法设置为spawn,这将导致启动的进程等待子线程,而不是像Stackoverflow question mentioned by the OP中提到的那样杀死它们。因此,下面是使用该方法的代码:

import multiprocessing as mp
from threading import Timer
import time

def print_time_every_5_seconds():
    print(time.ctime())
    Timer(5,print_time_every_5_seconds).start()


if __name__ == '__main__':
    mp.set_start_method('spawn')
    start_process = mp.Process(target=print_time_every_5_seconds)
    start_process.start()