相关疑难解决方法(0)

Python threading.timer - 每隔'n'秒重复一次

我对python计时器有困难,非常感谢一些建议或帮助:D

我不太了解线程如何工作,但我只是想每0.5秒触发一次函数,并能够启动和停止并重置计时器.

但是,RuntimeError: threads can only be started once当我执行threading.timer.start()两次时,我会继续得到.有没有解决这个问题?我threading.timer.cancel()在每次开始前尝试申请.

伪代码:

t=threading.timer(0.5,function)
while True:
    t.cancel()
    t.start()
Run Code Online (Sandbox Code Playgroud)

python python-2.7 python-3.x

75
推荐指数
6
解决办法
16万
查看次数

推迟python中的函数

在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本身并不是问题,但我无法对该方法进行单元测试.)

我知道线程是为不同步执行而设计的,但我想知道是否更容易,类似setTimeoutsetInterval存在.

python multithreading setinterval

10
推荐指数
2
解决办法
8449
查看次数

改进setInterval python的当前实现

我试图弄清楚如何制作一个在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", (), {}) …

python python-3.x

9
推荐指数
1
解决办法
5870
查看次数