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

2024-06-16 10:16:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个函数,允许我每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


Tags: 函数self间隔returntimeusedef错误
3条回答

注意这个:

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;)

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

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()

您遇到的主要语法错误是在if语句中省略了“:”。逻辑上,你的> 5应该是< 5。你知道吗

这张照片:

Let's Foo!
Wait 5 seconds
Wait 5 seconds
Wait 5 seconds
wait a bit now...
Let's Foo!

编辑: 这里是高级版本,其中wait_at_least装饰器 注意检查通话间隔时间的开销逻辑,以及 各种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()

我添加了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

您可以使用closure实现这一点

from time import time

def foo(t, time_to_wait):
   def _foo():
      if (time() - t) > time_to_wait:
         print(f"{time_to_wait} sec passed do something...")
      else:
         print(f"wait {time_to_wait} seconds")
   return _foo

In [14]: func = foo(time()) # pass the current time

In [15]: func()
wait 5 seconds
In [20]: func()
wait 5 seconds

In [21]: func()
5 sec passed do something...

相关问题 更多 >