Python 中 setInterval() 的等价物?
Python 是否有类似于 JavaScript 的 setInterval()
的函数?
我想要:
def set_interval(func, interval):
...
它将在每个 interval
时间单位调用 func
。
Does Python have a function similar to JavaScript's setInterval()
?
I would like to have:
def set_interval(func, interval):
...
That will call func
every interval
time units.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(25)
你也可以试试这个方法:
这样每隔5秒就会打印“5秒已过去”。
函数
sleep()
暂停执行指定的秒数。该参数可以是浮点数以指示更精确的睡眠时间。You can also try out this method:
So it will print "5 seconds has passed" every 5 seconds.
The function
sleep()
suspends execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time.上面的方法不太适合我,因为我需要能够取消间隔。我将该函数变成了一个类并提出了以下内容:
The above method didn't quite do it for me as I needed to be able to cancel the interval. I turned the function into a class and came up with the following:
上面的大多数答案都没有正确关闭线程。在使用 Jupyter Notebook 时,我注意到,当发送显式中断时,线程仍在运行,更糟糕的是,它们会从 1 个线程运行、2 个、4 个等开始不断增加。我下面的方法基于 @doom 的答案,但很干净通过在主线程中运行无限循环来侦听 SIGINT 和 SIGTERM 事件来处理
欢迎提出改进建议
Most of the answers above do not shut down the Thread properly. While using Jupyter notebook I noticed that when an explicit interrupt was sent, the threads were still running and worse, they would keep multiplying starting at 1 thread running,2, 4 etc. My method below is based on the answer by @doom but cleanly handles interrupts by running an infinite loop in the Main thread to listen for SIGINT and SIGTERM events
Feel free to suggest improvements
以上解决方案中,如果出现程序被关闭的情况,并不能保证它会正常关闭,总是建议通过杀软来关闭程序,大多数也没有停止的功能,我发现了一篇不错的文章在 Sankalp 编写的媒体上,它解决了这两个问题(在 python 中运行定期任务)请参阅随附的链接以获得更深入的了解。
在下面的示例中,使用名为 signal 的库来跟踪杀戮是软杀戮还是硬杀戮
In the above solutions if a situation arises where program is shutdown, there is no guarantee that it will shutdown gracefully,Its always recommended to shut a program via a soft kill, neither did most of them have a function to stop I found a nice article on medium written by Sankalp which solves both of these issues (run periodic tasks in python) refer the attached link to get a deeper insight.
In the below sample a library named signal is used to track the kill is soft kill or a hard kill
我已经编写了代码来在 python 中创建一个非常非常灵活的 setInterval 。在这里:
您可以获得许多功能和灵活性。运行此代码不会冻结您的代码,您可以在运行时更改间隔,您可以在运行时更改函数,您可以传递参数,您可以从函数中获取返回的对象等等。你也可以发挥你的技巧!
这是一个非常简单和基本的使用示例:
查看我的 Github 项目以查看更多示例并关注后续更新:D
https://github.com/Hzzkygcs/setInterval-python
I have written my code to make a very very flexible setInterval in python. Here you are:
You can get many features and flexibility. Running this code won't freeze your code, you can change the interval at run time, you can change the function at run time, you can pass arguments, you can get the returned object from your function, and many more. You can make your tricks too!
here's a very simple and basic example to use it:
Check out my Github project to see more examples and follow next updates :D
https://github.com/Hzzkygcs/setInterval-python
setInterval 应该在多线程上运行,并且在循环运行时不要冻结任务。
这是我支持多线程功能的RUNTIME包:
.pause, .resume : 暂停和恢复间隔
它简短而简单。注意,如果直接输入函数,python 需要 lambda,但 lambda 不支持命令块,因此您应该在将函数内容放入 setInterval 之前定义函数内容。
保存到文件 .py 并运行它。您将看到它打印随机数和字符串“AAAAA”。打印编号线程将在 1 秒后暂停打印并再次恢复打印 1 秒然后停止,而打印字符串保持打印文本不损坏。
如果您使用 OpenCV 进行图形动画,并使用 setInterval 来提高动画速度,则必须有 1 个主线程来应用 waitKey,否则无论延迟多慢或在子线程中应用 waitKey,窗口都会冻结:
setInterval should be run on multiple thread, and not freeze the task when it running loop.
Here is my RUNTIME package that support multithread feature:
.pause, .resume : pause and resume the interval
It's short and simple. Note that python need lambda if you input direct the function, but lambda is not support command block, so you should define the function content before put it in the setInterval.
Save to file .py and run it. You will see it print both random number and string "AAAAA". The print number thread will pause printing after 1 second and resume print again for 1 second then stop, while the print string keep printing text not corrupt.
In case you use OpenCV for graphic animation with those setInterval for boost animate speed, you must have 1 main thread to apply waitKey, otherwise the window will freeze no matter how slow delay or you applied waitKey in sub thread:
最近我也遇到了和你一样的问题。我找到了这些解决方案:
1。您可以使用该库: threading.Time(这有介绍上面)
2。您可以使用该库:sched(上面也有介绍)
<强>3。您可以使用该库:高级Python调度程序(推荐)
Recently, I have the same issue as you. And I find these soluation:
1. you can use the library: threading.Time(this have introduction above)
2. you can use the library: sched(this have introduction above too)
3. you can use the library: Advanced Python Scheduler(Recommend)
上面使用 func_wrapper 和 threading.Timer 的一些答案确实有效,只是它每次调用间隔时都会生成一个新线程,这会导致内存问题。
下面的基本示例通过将间隔放在单独的线程上,大致实现了类似的机制。它按照给定的时间间隔休眠。在开始编写代码之前,您需要了解以下一些限制:
JavaScript 是单线程的,因此当
setInterval
内的函数被触发时,其他任何东西都不会起作用。同时(不包括工作线程,但让我们讨论 setInterval 的一般用例。因此,线程是安全的。但在此实现中,除非使用 threading.rLock< /code>.下面的实现使用
。 time.sleep
来模拟interval,但是加上func
的执行时间,这个interval的总时间可能会比你预期的要长。因此,根据用例,您可能希望“少睡觉”(减去调用func
所花费的时间)我只是粗略测试了这一点,您绝对不应该像我一样使用全局变量,随意调整它以使其适合您的系统。
说得够多了,这里是代码:
预期输出:
Some answers above that uses
func_wrapper
andthreading.Timer
indeed work, except that it spawns a new thread every time an interval is called, which is causing memory problems.The basic example below roughly implemented a similar mechanism by putting interval on a separate thread. It sleeps at the given interval. Before jumping into code, here are some of the limitations that you need to be aware of:
JavaScript is single threaded, so when the function inside
setInterval
is fired, nothing else will be working at the same time (excluding worker thread, but let's talk general use case ofsetInterval
. Therefore, threading is safe. But here in this implementation, you may encounter race conditions unless using athreading.rLock
.The implementation below uses
time.sleep
to simulate intervals, but adding the execution time offunc
, the total time for this interval may be greater than what you expect. So depending on use cases, you may want to "sleep less" (minus time taken for callingfunc
)I only roughly tested this, and you should definitely not use global variables the way I did, feel free to tweak it so that it fits in your system.
Enough talking, here is the code:
Expected output:
我的 Python 3 模块
jsinterval.py
会很有帮助!这是:代码编辑:
修复了内存泄漏(由 @benjaminz 发现)。现在所有线程都在结束时被清理。为什么会发生这种泄漏?这是由于隐式(甚至显式)引用而发生的。就我而言,是
TIMEOUTS
和INTERVALS
。超时会自动自清理(在此补丁之后),因为它们使用函数包装器来调用该函数,然后自杀。但这是怎么发生的呢?除非所有引用也被删除或使用了 gc 模块,否则无法从内存中删除对象。解释:无法(在我的代码中)创建对超时/间隔的不需要的引用。他们只有一个引用:TIMEOUTS
/INTERVALS
字典。并且,当中断或完成时(只有超时才能不间断地完成),它们删除对自己的唯一现有引用:它们相应的 dict 元素。类使用__all__
完美封装,因此没有内存泄漏的空间。My Python 3 module
jsinterval.py
will be helpful! Here it is:CODE EDIT:
Fixed the memory leak (spotted by @benjaminz). Now ALL threads are cleaned up upon end. Why does this leak happen? It happens because of the implicit (or even explicit) references. In my case,
TIMEOUTS
andINTERVALS
. Timeouts self-clean automatically (after this patch) because they use function wrapper which calls the function and then self-kills. But how does this happen? Objects can't be deleted from memory unless all references are deleted too orgc
module is used. Explaining: there's no way to create (in my code) unwanted references to timeouts/intervals. They have only ONE referrer: theTIMEOUTS
/INTERVALS
dicts. And, when interrupted or finished (only timeouts can finish uninterrupted) they delete the only existing reference to themselves: their corresponding dict element. Classes are perfectly encapsulated using__all__
, so no space for memory leaks.这是一个低时间漂移解决方案,它使用线程定期向事件对象发出信号。线程的 run() 在等待超时时几乎不执行任何操作;因此时间漂移低。
Here is a low time drift solution that uses a thread to periodically signal an Event object. The thread's run() does almost nothing while waiting for a timeout; hence the low time drift.
入睡,直到下一个
秒
长度间隔开始:(非并发)简单且无漂移。
fall asleep until the next interval of
seconds
length starts: (not concurrent)simple and no drift.
这是我得到并测试过的明确解决方案。 setTimeout 是由其他人创建的,但我忘记了是谁。
Here's a definite solution I got and tested out which worked. The setTimeout one was created by someone else but I forgot who.
导入时间
def my_function():
print("函数已执行!")
Interval = 10 # 时间(以秒为单位)
while True:
我的函数()
时间.睡眠(间隔)
import time
def my_function():
print("Function executed!")
interval = 10 # time in seconds
while True:
my_function()
time.sleep(interval)
这是一些简单的事情:
Here's something easy peazy:
对 Python 没有真正的经验,但为什么我们不能:
Not really experienced with Python but why can't we just:
Python 中的情况有所不同:您需要
sleep()
(如果您想阻止当前线程)或启动一个新线程。请参阅http://docs.python.org/library/threading.htmlThings work differently in Python: you need to either
sleep()
(if you want to block the current thread) or start a new thread. See http://docs.python.org/library/threading.html来自 Python 文档:
From Python Documentation:
这可能是您正在寻找的正确片段:
This might be the correct snippet you were looking for:
这是一个可以启动和停止的版本。
它没有阻塞。
也没有任何故障,因为没有添加执行时间错误(对于例如音频等间隔很短的长时间执行很重要)
输出是:
This is a version where you could start and stop.
It is not blocking.
There is also no glitch as execution time error is not added (important for long time execution with very short interval as audio for example)
Output is :
只要保持美观和简单即可。
编辑:此代码是非阻塞的
Just keep it nice and simple.
EDIT : This code is non-blocking
稍微改变 Nailxx 的答案,你就得到了答案!
Change Nailxx's answer a bit and you got the answer!
sched
模块为一般 Python 代码提供这些功能。但是,正如其文档所建议的,如果您的代码是多线程的,则使用threading.Timer
类可能更有意义。The
sched
module provides these abilities for general Python code. However, as its documentation suggests, if your code is multithreaded it might make more sense to use thethreading.Timer
class instead.我认为这就是您所追求的:
如果您在重复方法末尾添加另一个条目到调度程序,它就会继续进行。
I think this is what you're after:
If you add another entry to the scheduler at the end of the repeating method, it'll just keep going.
我使用 sched 创建
setInterval
函数 要点I use sched to create
setInterval
function gist简单的 setInterval 实用程序
Simple setInterval utils