在Python中以给定的速率执行特定的语句

2023-12-22

我想编写一段代码,每秒执行指定次数的语句, 你们中的许多人可能更熟悉术语利率

这里我希望速率为每秒 30

假设我想每秒执行一个函数 30 次,持续 60 秒 表示速率=30/秒持续时间=60秒

任何人都可以告诉我他们的任何 api 都可以在 python 中执行相同的操作吗?


The sched模块正是用于此目的:

from __future__ import division
import sched
import time

scheduler = sched.scheduler(time.time, time.sleep)

def schedule_it(frequency, duration, callable, *args):
    no_of_events = int( duration / frequency )
    priority = 1 # not used, lets you assign execution order to events scheduled for the same time
    for i in xrange( no_of_events ):
        delay = i * frequency
        scheduler.enter( delay, priority, callable, args)

def printer(x):
    print x

# execute printer 30 times a second for 60 seconds
schedule_it(1/30, 60, printer, 'hello')
scheduler.run()

对于线程环境,使用sched.scheduler可以替换为threading.Timer:

from __future__ import division
import time
import threading

def schedule_it(frequency, duration, callable, *args, **kwargs):
    no_of_events = int( duration / frequency )
    for i in xrange( no_of_events ):
        delay = i * frequency
        threading.Timer(delay, callable, args=args, kwargs=kwargs).start()

def printer(x):
    print x

schedule_it(5, 10, printer, 'hello')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Python中以给定的速率执行特定的语句 的相关文章

随机推荐