【问题标题】:Schedule Tasks at Fixed Rate with Python Multiprocessing使用 Python 多处理以固定速率安排任务
【发布时间】:2016-01-25 13:40:41
【问题描述】:

我想在 Python 中异步运行一个函数,以固定的时间间隔重复调用该函数。 This 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 中实现这个功能?

这个post 是类似的,但要求一个进程中的解决方案。我想要一个多进程异步解决方案。

【问题讨论】:

    标签: python multiprocessing scheduled-tasks


    【解决方案1】:

    这是一种可能的解决方案。一个警告是 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()
    

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      相关资源
      最近更新 更多