[英]How do I run a function on a timer with a option to stop it on Python?
我正在处理一个 Python 项目,我在项目中有一个区域需要一个循环计时器,因为我需要检查代码,比如每 5 分钟一次,以查看数据库中的数据是否已更改,然后提醒用户. 现在我可以用if
语句等来完成大部分工作,但是计时器部分我不知道如何去做。
remind = (input('Would you like me to remind you of the status of your flight? yes/no: '))
if remind == 'yes':
# some how start a loop to check the database for update and give open to exit
print('Loop to check database')
elif remind == 'no':
print('Thank you for using FLIGHT CHECK')
quit()
所以我需要采取的步骤的基本逻辑是:
if remind = yes
check mysql table status
bunch of if statement
will also give option to stop alert
if remind = no
end
您可以使用 time 和 while 循环来监视变量的真/假。
import time
run = True
while run:
remind = (input('Would you like me to remind you of the status of your flight? yes/no: '))
if remind.lower() == 'yes':
print('database loop')
# Sleep for 300 seconds
time.sleep(300)
elif remind.lower() == 'no':
run = False
这将每 5 分钟循环一次,直到用户回答no
,此时它设置run = False
并结束 while 循环。
Would you like me to remind you of the status of your flight? yes/no: yes
database loop
Would you like me to remind you of the status of your flight? yes/no: no
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.