Python中的多线程重复器

0 投票
2 回答
525 浏览
提问于 2025-04-16 04:22

我有一个小的循环程序,它总是会结束。我该怎么做才能让它更稳定,不会崩溃,也不停止运行呢?我想在图形界面上加一个“心跳”功能,这样我就能看到它是否还在运行。在WxPython中,我的菜单栏会变成空白或者白色。

 def TimerSetup():
        import threading, time
        invl = 300

        def dothis():
            try:
                FetchUpdates()
            except Exception as e:
                pass

        class Repeat(threading.Thread):
            def run(self):
                dothis()

        if __name__ == '__main__':
            for x in range(7000):
                thread = Repeat(name = "Thread-%d" % (x + 1))
                thread.start()
                time.sleep(invl)

2 个回答

0

看起来你需要用 join() 来等待线程的开始。

 def TimerSetup():
        import threading, time
        invl = 300

        def dothis():
            try:
                FetchUpdates()
            except Exception as e:
                pass

        class Repeat(threading.Thread):
            def run(self):
                dothis()

        if __name__ == '__main__':
            for x in range(7000):
                thread = Repeat(name = "Thread-%d" % (x + 1))
                thread.start()
                thread.join()
                time.sleep(invl)
0

这个程序运行了7000次。所以如果你的运行时间大约是7000乘以300秒,那就“完全按照代码运行”了 :-) 不过,可能线程的数量或者你在FetchUpdates里做的事情可能会出问题。当它停止时,有没有什么错误信息?是不是达到了用户限制?

撰写回答