简体   繁体   English

你如何在 Python 中的某个时间启动一个函数?

[英]How do you start a function at a certain time in Python?

I have a list of timestamps, and I need to call a specific method when those timestamps are reached.我有一个时间戳列表,当达到这些时间戳时,我需要调用一个特定的方法。 Those timestamps are roughly 20ms apart.这些时间戳大约相隔 20 毫秒。

At the moment I am using busy waiting in a separate thread, but I am worried about the CPU overload.目前我在一个单独的线程中使用忙等待,但我担心 CPU 过载。 Example :例子 :

while True:
  if myTimestamp > time.time():
    mymethod()

or或者

while myTimestamp < time.time():
   time.sleep(0.1)
mymethod()

Is there a more efficient way to do it ?有没有更有效的方法来做到这一点? Thanks谢谢

There are several ways -- some are more easily portable to different operating systems than others.有几种方法——有些方法比其他方法更容易移植到不同的操作系统。

Generally, what you could do is:一般来说,你可以做的是:

  1. spawn a new thread for every task为每个任务生成一个新线程
  2. in each thread, get the current time, and time.sleep() for the remaining time在每个线程中,获取当前时间,剩余时间 time.sleep()

That works, but it's not extremely accurate.这有效,但它不是非常准确。 You can make your life a little easier by using the sched module that comes with python (it basically does what I describe above, but might be a bit more clever).你可以通过使用 python 附带的sched模块让你的生活更轻松一些(它基本上完成了我上面描述的内容,但可能更聪明一点)。

If you need microsecond accuracy ("hard" real time constraints), python is not the tool of choice.如果您需要微秒精度(“硬”实时约束),python 不是首选工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM