为了账号安全,请及时绑定邮箱和手机立即绑定

相当于setInterval()的Python吗?

相当于setInterval()的Python吗?

Smart猫小萌 2019-11-30 14:43:58
Python是否具有类似于JavaScript的功能setInterval()?谢谢
查看完整描述

3 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

这可能是您正在寻找的正确片段:


import threading


def set_interval(func, sec):

    def func_wrapper():

        set_interval(func, sec)

        func()

    t = threading.Timer(sec, func_wrapper)

    t.start()

    return t


查看完整回答
反对 回复 2019-11-30
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

这是您可以启动和停止的版本。它没有阻塞。由于没有添加执行时间错误,因此也没有毛刺(例如,对于音频间隔很短的长时间执行很重要)


import time, threading


StartTime=time.time()


def action() :

    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))



class setInterval :

    def __init__(self,interval,action) :

        self.interval=interval

        self.action=action

        self.stopEvent=threading.Event()

        thread=threading.Thread(target=self.__setInterval)

        thread.start()


    def __setInterval(self) :

        nextTime=time.time()+self.interval

        while not self.stopEvent.wait(nextTime-time.time()) :

            nextTime+=self.interval

            self.action()


    def cancel(self) :

        self.stopEvent.set()


# start action every 0.6s

inter=setInterval(0.6,action)

print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))


# will stop interval in 5s

t=threading.Timer(5,inter.cancel)

t.start()

输出为:


just after setInterval -> time : 0.0s

action ! -> time : 0.6s

action ! -> time : 1.2s

action ! -> time : 1.8s

action ! -> time : 2.4s

action ! -> time : 3.0s

action ! -> time : 3.6s

action ! -> time : 4.2s

action ! -> time : 4.8s


查看完整回答
反对 回复 2019-11-30
?
拉丁的传说

TA贡献1789条经验 获得超8个赞

只要保持它的美观和简单即可。


import threading


def setInterval(func,time):

    e = threading.Event()

    while not e.wait(time):

        func()


def foo():

    print "hello"


# using

setInterval(foo,5)


# output:

hello

hello

.

.

.

编辑:此代码是非阻塞的


import threading


class ThreadJob(threading.Thread):

    def __init__(self,callback,event,interval):

        '''runs the callback function after interval seconds


        :param callback:  callback function to invoke

        :param event: external event for controlling the update operation

        :param interval: time in seconds after which are required to fire the callback

        :type callback: function

        :type interval: int

        '''

        self.callback = callback

        self.event = event

        self.interval = interval

        super(ThreadJob,self).__init__()


    def run(self):

        while not self.event.wait(self.interval):

            self.callback()




event = threading.Event()


def foo():

    print "hello"


k = ThreadJob(foo,event,2)

k.start()


print "It is non-blocking"


查看完整回答
反对 回复 2019-11-30
  • 3 回答
  • 0 关注
  • 1157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号