Python有类似于JavaScript的功能setInterval()吗?
谢谢
我正在开发一个Django应用程序.我有一个API端点,如果需要,它必须执行一个必须重复几次的函数(直到某个条件为真).我现在如何处理它是 -
def shut_down(request):
# Do some stuff
while True:
result = some_fn()
if result:
break
time.sleep(2)
return True
Run Code Online (Sandbox Code Playgroud)
虽然我知道这是一个可怕的方法,我不应该阻止2秒,我无法弄清楚如何解决它.
在等了4秒之后,这有效.但我想要让循环在后台运行的东西,并在some_fn返回True时停止.(另外,some_fn肯定会返回True)
编辑 -
阅读Oz123的回复给了我一个似乎有效的想法.这就是我做的 -
def shut_down(params):
# Do some stuff
# Offload the blocking job to a new thread
t = threading.Thread(target=some_fn, args=(id, ), kwargs={})
t.setDaemon(True)
t.start()
return True
def some_fn(id):
while True:
# Do the job, get result in res
# If the job is done, return. Or sleep the thread for 2 seconds before trying again.
if …Run Code Online (Sandbox Code Playgroud) 我最近发布了一个关于如何推迟在Python中执行函数的问题(类似于Javascript setTimeout),结果证明这是一个简单的任务threading.Timer(好吧,只要函数不与其他代码共享状态,但这会在任何事件驱动的环境中产生问题).
现在我想做得更好并效仿setInterval.对于那些不熟悉Javascript的人,setInterval允许每隔x秒重复一次对函数的调用,而不会阻止其他代码的执行.我创建了这个示例装饰器:
import time, threading
def setInterval(interval, times = -1):
# This will be the actual decorator,
# with fixed interval and times parameter
def outer_wrap(function):
# This will be the function to be
# called
def wrap(*args, **kwargs):
# This is another function to be executed
# in a different thread to simulate setInterval
def inner_wrap():
i = 0
while i != times:
time.sleep(interval)
function(*args, **kwargs)
i += 1 …Run Code Online (Sandbox Code Playgroud) 在JavaScript中,我习惯于能够调用稍后要执行的函数,就像这样
function foo() {
alert('bar');
}
setTimeout(foo, 1000);
Run Code Online (Sandbox Code Playgroud)
这不会阻止其他代码的执行.
我不知道如何在Python中实现类似的东西.我可以睡觉
import time
def foo():
print('bar')
time.sleep(1)
foo()
Run Code Online (Sandbox Code Playgroud)
但这会阻止其他代码的执行.(实际上在我的情况下阻塞Python本身并不是问题,但我无法对该方法进行单元测试.)
我知道线程是为不同步执行而设计的,但我想知道是否更容易,类似setTimeout或setInterval存在.
我试图弄清楚如何制作一个在python中取消的setInterval而不需要创建一个完整的新类,我想出了如何但现在我想知道是否有更好的方法来做到这一点.
下面的代码似乎工作正常,但我没有彻底测试它.
import threading
def setInterval(func, sec):
def inner():
while function.isAlive():
func()
time.sleep(sec)
function = type("setInterval", (), {}) # not really a function I guess
function.isAlive = lambda: function.vars["isAlive"]
function.vars = {"isAlive": True}
function.cancel = lambda: function.vars.update({"isAlive": False})
thread = threading.Timer(sec, inner)
thread.setDaemon(True)
thread.start()
return function
interval = setInterval(lambda: print("Hello, World"), 60) # will print Hello, World every 60 seconds
# 3 minutes later
interval.cancel() # it will stop printing Hello, World
Run Code Online (Sandbox Code Playgroud)
有没有办法在不创建继承threading.Thread或使用的专用类的情况下执行上述操作type("setInterval", (), {}) …
因此,threading模块有一个Timer类从Thread类中反复执行某些任务.
我想知道为什么多处理模块没有类似于类似的TimedProcess类,例如,它是否Process反复执行某些任务?
可以编写这样一个定时的过程,我写了一个,但仍然很好奇.或者我错过了什么?
我所能得到的所有示例都没有真正解决我的问题,即后台中的某个程序不断循环,而程序的其余部分仍在继续。
下面是一个使用 _thread 的简单方法示例:
import _thread
import time
def countSeconds():
time.sleep(1)
print("Second")
_thread.start_new(countSeconds, ())
def countTenSeconds():
time.sleep(10)
print("Ten seconds passed")
_thread.start_new(countTenSeconds, ())
_thread.start_new(countSeconds, ())
_thread.start_new(countTenSeconds, ())
Run Code Online (Sandbox Code Playgroud)
忽略一个明显的事实,即我们可以跟踪秒数,并且如果它是十的倍数,则只打印不同的内容,我将如何更有效地创建它。
在我的实际程序中,线程似乎会消耗大量内存,我假设是通过创建线程的多个实例来实现的。我是否必须在每个过程结束时“start_new”线程?
谢谢你的帮助。
如果我调用一个没有如下参数的函数,我想每隔3秒执行一次函数代码:
def mytempfunc():
print "this is timer!"
threading.Timer(5, mytempfunc).start()
Run Code Online (Sandbox Code Playgroud)
但如果我用这样的参数调用一个函数:
def myotherfunc(a,b,c,d):
print "this is timer!"
threading.Timer(5, myotherfunc(a,b,c,d)).start()
Run Code Online (Sandbox Code Playgroud)
新线程将立即创建并启动,无需等待5秒钟.有什么我错过的吗?