在给定时间安排一个函数运行 - Python
Schedule at given time meanwhile a function runs - Python
我一直在 Python 中搜索不同的时间表,例如 Sched(我是 Windows 用户)等。但是我无法真正掌握它,我也不知道如果可能的话。我的计划是像下图这样:
我们可以在 Time:00.21 处看到我希望程序执行功能 2 的时间,但是功能 1 应该添加到我在列表中尽可能多的列表中它会在计时器响起前 2 分钟开始工作。基本上...
功能 1 在计时器前 2 分钟执行其功能。当它点击 00:21 时,然后停止函数 1 并执行函数 2,它获取 List 并在其自己的函数中使用它,当它完成时,它就完成了。
但是我不知道该怎么做或如何开始。我想做一个自己的计时器,但感觉这不是解决方案。大家有什么建议吗?
我想我会通过创建一个子class 是threading.Thread
的class 来解决这样的问题。从那里,你用你想要执行的功能覆盖 run
方法,在这种情况下,它将把东西放在一个列表中。然后,在 main
中启动该线程,然后调用 sleep
。 class 看起来像这样:
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 并且您应该被设置。
我一直在 Python 中搜索不同的时间表,例如 Sched(我是 Windows 用户)等。但是我无法真正掌握它,我也不知道如果可能的话。我的计划是像下图这样:
我们可以在 Time:00.21 处看到我希望程序执行功能 2 的时间,但是功能 1 应该添加到我在列表中尽可能多的列表中它会在计时器响起前 2 分钟开始工作。基本上...
功能 1 在计时器前 2 分钟执行其功能。当它点击 00:21 时,然后停止函数 1 并执行函数 2,它获取 List 并在其自己的函数中使用它,当它完成时,它就完成了。
但是我不知道该怎么做或如何开始。我想做一个自己的计时器,但感觉这不是解决方案。大家有什么建议吗?
我想我会通过创建一个子class 是threading.Thread
的class 来解决这样的问题。从那里,你用你想要执行的功能覆盖 run
方法,在这种情况下,它将把东西放在一个列表中。然后,在 main
中启动该线程,然后调用 sleep
。 class 看起来像这样:
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 并且您应该被设置。