我如何同时运行计时器和其他功能,以应对计时器返回几点? [Python]

问题描述 投票:0回答:2

我有一个计时器,返回(至少我希望它有)一些值。我在计时器类之外有一个函数,该函数应查看计时器的返回值,以及该函数是否接收到特定数据-仅在该特定时刻执行其他操作。

from time import time, sleep

class Clock:
    def __init__(self):
        self.oneSec = 0
        self.secsPassed = 0 #counts all seconds that already passed, up to 59; then resets and counts again
        self.minute = 0
        self.hour = 0 #currently unused
        self.day = 0 #currently unused
        self.start_time = 0

        self.start()

    def start(self):
        while self.secsPassed < 10:
            self.start_time = time()
            sleep(1)
            self.oneSec = int(time() - self.start_time) #easiest way to measure a second
            self.secsPassed += self.oneSec
            print(f"{self.minute} minutes, {self.secsPassed} seconds")
            self.getStats() #returns values without breaking the loop, at least I hope it does 

            if self.secsPassed == 10: #normally it'd be 59, but I wanted to do it quicker for sake of tests
                self.secsPassed = -1 #with 0 after 1:59 minute there would be immediately 2:01
                self.minute += 1

            if self.minute == 2 and self.secsPassed == 0: #just to end test if everything works fine
                break #for some reason it doesn't totally exit whole code, only stops counting, but I still have to manually exit the code from running


    def getStats(self):
        return self.day, self.hour, self.minute, self.secsPassed

现在,我需要在Clock类之外的一个函数,该函数可以观察Clock的return语句如何更改并对它们做出相应的反应。我已经做过一些编码,但是它不能工作,我可能知道为什么,但是我不能在3个小时内提出解决方案。这是我当前的代码:

def clockChecker(clock):
    while True: #I thought it'd be a good idea to loop since it has to be "conscious" the whole time to react on new returns, but... I guess this cannot work, after a few hours I realized that by running this function it gets the returned statement only once, so it can't update
        if clock == (0, 0, 0, 3): #if clocks makes 3rd second
            print("It works!")
            break

我曾尝试使用线程,管道和池,但是如果我的clockChecker无效,则无济于事。首先,我的ClockChecker绝对需要帮助,其次,我非常感谢您的帮助,至少可以选择应该使用的那个(线程,管道,池),因此它运行起来非常流畅。

python timer python-multithreading simultaneous
2个回答
0
投票

使用方法会发现一些困难。

首先只是clockChecker函数,我相信您缺少使该工作有效的.getStats()调用,它没有成功的机会。

即使进行此更改(应该起作用),完全匹配也是非常危险的,并且会遭受“在正确的时间不匹配”和“也许永远不匹配”的痛苦。

处理此问题的一种方法是使用>=或其他比特定瞬间更匹配的条件。其他包括:threading.Event;带有将条件推入计时器的挂钩;睡眠三秒钟按原样执行逻辑;协程,还有更多:)


0
投票

如果您不介意更改为其他路线,则>

def outside_func():
    do something
    return

class clock():
    def __init__(self, arguments):
        self.secspassed
    def timer():
        while True:
            self.secspasswd += 1
            if self.secspasswd % 3 == 0:
                outside_func()
            time.sleep(1)   

我认为使用+1来获取时间值会导致偏差增加。设置+1需要一些时间,设置属性值也需要一些时间。 +1

时,实时时间已经超过1秒
© www.soinside.com 2019 - 2024. All rights reserved.