使用Python Multiprocessing定时执行任务

3

我想在Python中异步运行一个函数,并以固定时间间隔不断调用该函数。这个Java类(链接)有类似于我所需的功能。我希望能够在Python中找到类似的东西:

pool = multiprocessing.Pool()
pool.schedule(func, args, period)
# other code to do while that runs in the background
pool.close()
pool.join()

有提供类似功能的包吗?我更喜欢简单和轻量级的东西。

我该如何在python中实现这个功能?

这个帖子很相似,但是要求在进程内解决。我想要一个多进程异步解决方案。

1个回答

0
这里有一个可能的解决方案。一个警告是,func需要比rate更快地返回,否则它不会像rate一样频繁调用,如果它变得更快,它将在赶上时比rate更快地被调度。这种方法似乎需要很多工作,但并行编程通常是困难的。我会很感激第二次查看代码以确保我没有在等待某个死锁。
import multiprocessing, time, math


def func():
    print('hello its now {}'.format(time.time()))


def wrapper(f, period, event):
    last = time.time() - period
    while True:
        now = time.time()

        # returns True if event is set, otherwise False after timeout
        if event.wait(timeout=(last + period - now)):
            break
        else:
            f()
            last += period


def main():
    period = 2
    # event is the poison pill, setting it breaks the infinite loop in wrapper
    event = multiprocessing.Event()
    process = multiprocessing.Process(target=wrapper, args=(func, period, event))
    process.start()

    # burn some cpu cycles, takes about 20 seconds on my machine
    x = 7
    for i in range(50000000):
        x = math.sqrt(x**2)

    event.set()
    process.join()
    print('x is {} by the way'.format(x))

if __name__ == '__main__':
    main()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接