[英]How to create a “timer” in python?
Is it possible to make the script drop everything it's been doing if a timer hits a certain time?如果计时器达到某个时间,是否可以让脚本放弃它一直在做的所有事情?
Let's say I want it to run for 24 hours and after that it should print a few things and then exit.假设我希望它运行 24 小时,然后它应该打印一些东西然后退出。
This is a pretty rude method but it will work.这是一种非常粗鲁的方法,但它会起作用。 REMEMBER: put your code after the else statement or it won't work.
请记住:将您的代码放在 else 语句之后,否则它将不起作用。 Also, modify the comment above exit() as the comment said.
此外,按照评论所述修改 exit() 上方的评论。 PS.: this are built-in modules.
PS.:这是内置模块。 No need to install anything.
无需安装任何东西。
import datetime
from sys import exit
starting_time = datetime.datetime.now()
while True:
actual_datetime = datetime.datetime.now()
if actual_datetime > starting_time + datetime.timedelta(days=1):
# do what you need to do before it shut down
exit()
else:
# RUN YOUR PROGRAM HERE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.