在python中使用函数的延迟计时器

在python中使用函数的延迟计时器,python,python-2.7,Python,Python 2.7,我想做一个函数,允许我每5秒使用另一个函数。当函数的第一次调用启动时,另一个变量将存储上次执行时间。。我计算了5秒的时间间隔,如果5秒没有过去,就返回 class MyClass(): def __init__(self): last_use = 0 def __del__(self): pass def Foo(self): elapsed = time.time() - self.GetLastClick()

我想做一个函数,允许我每5秒使用另一个函数。当函数的第一次调用启动时,另一个变量将存储上次执行时间。。我计算了5秒的时间间隔,如果5秒没有过去,就返回

class MyClass():
    def __init__(self):
        last_use = 0
    def __del__(self):
        pass

    def Foo(self):
        elapsed = time.time() - self.GetLastClick()

        if (elapsed > 5)
            print("Wait 5 seconds")
            return

        self.SetLastClick(time.time())

    def SetLastClick(self, arg):
        self.last_use = arg

    def GetLastClick(self):
        return self.last_use
但是这不起作用,我做错了什么? 我会遇到一些错误,比如无效语法,还有一些关于float的错误
Python27

您可以使用


注意这个:

import time

class MyClass():
    def __init__(self):
        self.last_use = 0
    def __del__(self):
        pass

    def Foo(self):
        if(self.last_use == 0):
            print "Started calling Foo"
            self.last_use = time.time
            time.sleep(5)
            self.anotherFunc()
        else:
            self.whileWaiting()

    def anotherFunc(self):
        self.last_use = 0;
        print "called after 5 second"

    def whileWaiting(self):
        print "Hey! I'm waiting while the previous call ends"


obj = MyClass()
obj.Foo();

PS:我喜欢JavaScript;)

这是您的代码,经过清理,可以删除Python中不需要的类似Java的getter/setter:

import time

class MyClass():
    def __init__(self):
        self.last_use = 0

    def Foo(self):
        elapsed = time.time() - self.last_use

        if elapsed < 5:
            print("Wait 5 seconds")
            return

        self.last_use = time.time()
        print("Let's Foo!")


mc = MyClass()
mc.Foo()
mc.Foo()
mc.Foo()
mc.Foo()
print('wait a bit now...')
time.sleep(5)
mc.Foo()
编辑: 这是一个高级版本,其中一个
wait\u至少
decorator需要
注意检查调用之间经过的时间的开销逻辑,以及
各种
FooX()
方法只做
FooX()
方法所做的事情:

def wait_at_least(min_wait_time):
    "a decorator to check if a minimum time has elapsed between calls"
    def _inner(fn):
        # a wrapper to define the last_call value to be preserved 
        # across function calls
        last_call = [0]
        def _inner2(*args, **kwargs):
            # the function that will actually be called, checking the
            # elapsed time and only calling the function if enough time
            # has passed
            elapsed = time.time() - last_call[0]
            if elapsed < min_wait_time:
                msg = "must wait {:.2f} seconds before calling {} again".format(min_wait_time - elapsed, fn.__name__)
                print(msg)
                # consider doing 'raise NotYetException(msg, min_wait_time, elapsed)` 
                # instead of just returning
                return
            last_call[0] = time.time()
            return fn(*args, **kwargs)
        return _inner2
    return _inner


class MyClass():
    def __init__(self):
        pass

    @wait_at_least(5)
    def Foo(self):
        print("Let's Foo!")

    @wait_at_least(3)
    def Foo2(self):
        print("We can Foo2!")


mc = MyClass()
mc.Foo()
mc.Foo2()
mc.Foo()
mc.Foo2()
time.sleep(1.5)
mc.Foo()
mc.Foo2()
print('wait a bit now...')
time.sleep(3)
mc.Foo()
mc.Foo2()
print('wait a little bit more...')
time.sleep(2)
mc.Foo()
mc.Foo2()

“我想做一个功能,允许我每5秒使用另一个功能”。你是说一个函数每5秒调用另一个函数吗?不,是一个函数使用的延迟。使用Foo函数,等待5秒,只有在5秒过后才可能再次使用Foo“这不起作用”如何?它的作用是什么?它与您预期的行为有何不同?遗憾的是,您的代码甚至不可执行。外部的
foo()
可以自己执行
t=time()
,而不是让调用者传入。如果您已经在def foo中检查了秒数,为什么要执行time.sleep(5)?因此,我的测试代码将在再次调用foo()之前等待所需的时间。我只有一个错误。全局名称'appeased'未定义,我使用decoratory,您应该在
\u inner2
中使用'not-yet'大小写引发异常,而不是仅仅返回。在异常中,您可以将剩余的等待时间作为异常的属性传递回去,并将当前打印字符串作为异常消息传递回去。请参阅代码编辑(NotYetException声明作为练习离开)。优雅的解决方案
import time

class MyClass():
    def __init__(self):
        self.last_use = 0

    def Foo(self):
        elapsed = time.time() - self.last_use

        if elapsed < 5:
            print("Wait 5 seconds")
            return

        self.last_use = time.time()
        print("Let's Foo!")


mc = MyClass()
mc.Foo()
mc.Foo()
mc.Foo()
mc.Foo()
print('wait a bit now...')
time.sleep(5)
mc.Foo()
Let's Foo!
Wait 5 seconds
Wait 5 seconds
Wait 5 seconds
wait a bit now...
Let's Foo!
def wait_at_least(min_wait_time):
    "a decorator to check if a minimum time has elapsed between calls"
    def _inner(fn):
        # a wrapper to define the last_call value to be preserved 
        # across function calls
        last_call = [0]
        def _inner2(*args, **kwargs):
            # the function that will actually be called, checking the
            # elapsed time and only calling the function if enough time
            # has passed
            elapsed = time.time() - last_call[0]
            if elapsed < min_wait_time:
                msg = "must wait {:.2f} seconds before calling {} again".format(min_wait_time - elapsed, fn.__name__)
                print(msg)
                # consider doing 'raise NotYetException(msg, min_wait_time, elapsed)` 
                # instead of just returning
                return
            last_call[0] = time.time()
            return fn(*args, **kwargs)
        return _inner2
    return _inner


class MyClass():
    def __init__(self):
        pass

    @wait_at_least(5)
    def Foo(self):
        print("Let's Foo!")

    @wait_at_least(3)
    def Foo2(self):
        print("We can Foo2!")


mc = MyClass()
mc.Foo()
mc.Foo2()
mc.Foo()
mc.Foo2()
time.sleep(1.5)
mc.Foo()
mc.Foo2()
print('wait a bit now...')
time.sleep(3)
mc.Foo()
mc.Foo2()
print('wait a little bit more...')
time.sleep(2)
mc.Foo()
mc.Foo2()
Let's Foo!
We can Foo2!
must wait 5.00 seconds before calling Foo again
must wait 3.00 seconds before calling Foo2 again
must wait 3.50 seconds before calling Foo again
must wait 1.50 seconds before calling Foo2 again
wait a bit now...
must wait 0.50 seconds before calling Foo again
We can Foo2!
wait a little bit more...
Let's Foo!
must wait 1.00 seconds before calling Foo2 again