【问题标题】:Schedule at given time meanwhile a function runs - Python在给定时间安排一个函数运行的同时 - Python
【发布时间】:2018-02-19 19:58:55
【问题描述】:

我一直在寻找 Python 中的不同时间表,例如 Sched(我是 Windows 用户)等。但是我无法真正掌握它,我不知道它是否可能。我的计划是制作如下图:

我们可以在 Time:00.21 等时间看到我希望程序执行功能 2 但功能 1 应该添加到列表中,因为它在 2 分钟前工作计时器响起。基本上...

函数 1 在计时器前 2 分钟执行它的函数。当它到达 00:21 时,停止函数 1 并执行函数 2,它获取列表并在自己的函数中使用它,当它完成时,它就完成了。

但是我不知道如何执行此操作或开始。我正在考虑做一个自己的计时器,但感觉这不是解决方案。大家有什么建议?

【问题讨论】:

    标签: python scheduled-tasks schedule


    【解决方案1】:

    我想我会通过创建一个子类threading.Thread 的类来解决这样的问题。从那里,你用你想要执行的函数覆盖run 方法,在这种情况下,它将把东西放在一个列表中。然后,在main 中,您启动该线程,然后调用sleep。该类将如下所示:

    class ListBuilder(threading.Thread):
        def__init__(self):
            super().__init__()
            self._finished = False
    
            self.lst = []
    
        def get_data():
            # This is the data retrieval function
            # It could be imported in, defined outside the class, or made static.
    
        def run(self):
            while not self._finished:
                self.lst.append(self.get_data())
    
        def stop(self):
            self._finished = True
    

    你的main 看起来像

    import time
    
    if __name__ == '__main__':
        lb = ListBuilder()
        lb.start()
    
        time.sleep(120)  # sleep for 120 seconds, 2 minutes
    
        lb.stop()
        time.sleep(.1)  # A time buffer to make sure the final while loop finishes
                        # Depending on how long each while loop iteration takes,
                        # it may not be necessary or it may need to be longer
    
        do_stuf(lb.lst)  # performs actions on the resulting list
    

    现在,您所要做的就是使用 Windows 任务计划程序在 00:19 运行它,您应该已做好准备。

    【讨论】:

    • 非常感谢!这就是我一直在寻找的答案! :)
    猜你喜欢
    • 2019-06-27
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 2017-11-16
    • 2022-11-30
    • 1970-01-01
    相关资源
    最近更新 更多