在Python中等待定时器到期的异步等待

huangapple go评论68阅读模式
英文:

Asyncro wait for a timer to expire in Python

问题

所以
我来到了嵌入式编程中的C语言部分那里有一个名为`HAL_SYSTICK_Callback`的函数在每个时钟周期都会被执行通过它知道了CPU时钟你可以像这样创建定时器

    t_1ms = 1
    
    if(t_1ms)
       t_1ms--;

然后在主代码中检查 `if(!t_1ms) 做一些事情`

现在我想在Python中做类似的事情在代码的某个特定点加载一个计时器然后在代码的另一个部分检查计时器是否过期

在执行代码时计时器必须自行计数而不会阻塞主代码

我看到了像[waiting][1]这样的库但它们似乎都是阻塞的

[1]: https://pypi.org/project/waiting/
英文:

So,
I come to C in embedded programming where there's the function HAL_SYSTICK_Callback which is executed on every clock tick. With it, knowing the CPU clock, you can create timers in a way like

t_1ms = 1

if(t_1ms)
   t_1ms--;

And in the main code check if if(!t_1ms) do something

Now, I would like to do something like this in Python where, at a certain point in the code I load a timer and then in another part of the code, I check if the timer is exprired.

While executing the code, the timer must count by its onw without blocking the main code.

I've see libraries like waiting but they all seem blocking.

答案1

得分: 0

根据matszwecja的建议,使用time.monotonic()对我的用例来说已经足够了。

import time

start = time.monotonic()
# 执行某些操作的代码
end = time.monotonic()
if end - start > 1:
   # 检查是否花费了超过1秒的时间
   # 执行其他操作
英文:

As suggest by matszwecja, the use of time.monotonic() is more than sufficient for my use case

import time

start = time.monotonic()
# code that does something
end = time.monotonic()
if end - start > 1:
   # check if more than 1 second has been spent
   # do something else

huangapple
  • 本文由 发表于 2023年6月13日 18:44:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76464077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定