Skip to main content
 首页 » 编程设计

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

2025年05月04日13oomusou

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

这里我希望速率为每秒 30

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

谁能告诉我他们在 python 中提供的任何 api 都可以做同样的事情吗?

请您参考如下方法:

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')