用Python实现一个毫秒级Timer,间隔执行各种任务

问题

如果想间隔一定时间发送一些数据,或者处理某一个任务,python里面比较简单的实现方式是sleep,但是简单的sleep会随着任务的持续执行,和最开始的时间偏离越来越大。主要原因有两个

  1. python中sleep执行的时间并不精确,难以做到毫秒级的精度
  2. 任务本身执行的时候会和sleep执行的时间累加

为了解决上面两个问题,设计了下面的代码

实现

from time import sleep, time


class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self.interval = interval
        self.function = function
        self.is_running = False
        self.args = args
        self.kwargs = kwargs
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        start = int(time() * 1000)
        i = 0
        if not self.is_running:
            self.is_running = True

            while True:
                if not self.is_running:
                    break

                i += 1
                now = int(time() * 1000)
                sleep_ms = i * self.interval - (now - start)
                if sleep_ms < 0:
                    self.function(*self.args, **self.kwargs)
                else:
                    sleep(sleep_ms / 1000.0)
                    self.function(*self.args, **self.kwargs)

    def stop(self):
        self.is_running = False

使用

def hello(name):
    print(f"[{time()}]\t Hello {name}!")
    sleep(0.01)


print("starting...")

rt = RepeatedTimer(100, hello, "world")
try:
    sleep(50)
finally:
    rt.stop()

参考

https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 中,你可以使用 `time` 模块和 `threading` 模块来实现毫秒定时器。 下面是一个使用 `time` 模块的例子: ```python import time def timer_callback(): # 在这里编写你想要执行的定时任务 print("定时任务执行") def start_timer(interval): while True: start_time = time.time() # 记录开始时间 timer_callback() # 执行定时任务 elapsed_time = time.time() - start_time # 计算已经过去的时间 time.sleep(max(0, interval - elapsed_time)) # 根据设定的时间间隔和已经过去的时间计算需要延迟的时间 # 使用毫秒的时间间隔调用定时器,这里设置为每 100 毫秒执行一次 start_timer(0.1) ``` 这个例子中,`timer_callback` 函数是你想要执行的定时任务。`start_timer` 函数会在一个无限循环中调用 `timer_callback`,并根据设定的时间间隔计算需要延迟的时间。 如果你需要更精确的定时器,可以考虑使用 `threading` 模块中的 `Timer` 类。下面是一个使用 `Timer` 类的例子: ```python import threading def timer_callback(): # 在这里编写你想要执行的定时任务 print("定时任务执行") def start_timer(interval): timer = threading.Timer(interval / 1000, timer_callback) # 创建一个定时器对象 timer.start() # 启动定时器 # 使用毫秒的时间间隔调用定时器,这里设置为每 100 毫秒执行一次 start_timer(100) ``` 这个例子中,`timer_callback` 函数是你想要执行的定时任务。`start_timer` 函数会创建一个 `Timer` 对象,并设定定时器的时间间隔。然后启动定时器,定时任务会在设定的时间间隔执行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值