【问题标题】:How to pause/sleep() function without crashing app?如何在不崩溃应用程序的情况下暂停/睡眠()功能?
【发布时间】:2021-11-02 06:06:03
【问题描述】:

我有一个应用程序,我正在尝试每分钟添加网站更新。这部分目前工作得很好。我在当前这段代码摘录中遇到的问题是,当我关闭/退出应用程序时,我必须按几次“X”按钮,它会完全崩溃并死机。

如果我的理解是正确的,我相信这种情况正在发生,因为当我尝试退出时,time.sleep() 仍在不断“运行”。

如何运行这样的定期更新,当我想关闭它时不会让应用程序陷入困境?有人可以在这里帮我解决吗?

我在这里的这个工作示例中只添加了 5 秒的睡眠时间,而不是我预期的 60 秒,以便在您测试时节省时间。

import time
from threading import Thread
from kivy.app import App

class Test(App):
    def build(self):
        self.thread_for_update()

    def thread_for_update(self):
        p1 = Thread(target=lambda: self.check_for_update())
        p1.start()

    def check_for_update(self):
        time.sleep(5)
        print("Update")
        # Here I'm checking an online data source for changes
        # I will also notify user if theres changes
        self.thread_for_update()
Test().run()

【问题讨论】:

    标签: python multithreading function time sleep


    【解决方案1】:

    您可以使用threading.Timer,并在另一个函数中更新它。

    threading.Timer 有 2 个参数,延迟(以秒为单位)和要调用的函数。

    def check_for_update(self):
            Timer(5, self.update).start()
            
    
    def update(self):
            print("Update")
            self.thread_for_update()
    

    【讨论】:

    • 感谢您的回复,我已经尝试过您的方法,也尝试过使用和不使用线程的不同方式运行它,但是当我关闭应用程序时,它似乎仍然很糟糕。这可能与线程有关吗?
    【解决方案2】:

    我想我可能已经修好了。当我添加p1.daemon = True 时,当我尝试退出时,它似乎很好地退出了程序。

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 2021-06-17
      • 2021-04-07
      相关资源
      最近更新 更多