代码之家  ›  专栏  ›  技术社区  ›  PW1990

如何暂停/sleep()函数而不使应用程序崩溃?

  •  0
  • PW1990  · 技术社区  · 4 年前

    我有一个应用程序,我正试图添加网站更新到每一分钟。那部分目前还不错。我在当前代码摘录中遇到的问题是,当我关闭/退出应用程序时,我必须按下“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()
    
    1 回复  |  直到 4 年前
        1
  •  0
  •   pxDav    4 年前

    你可以用 threading.Timer ,并在另一个函数中进行更新。

    穿线。计时器 接受2个参数、延迟(秒)和要调用的函数。

    def check_for_update(self):
            Timer(5, self.update).start()
            
    
    def update(self):
            print("Update")
            self.thread_for_update()
    
        2
  •  0
  •   PW1990    4 年前

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

    推荐文章