python - 如何在计时器上运行一个函数,并选择在 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
解决方案
您可以使用时间和 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
>>>
推荐阅读
- java - Firestore Query 循环多次
- javascript - 如何使表格中的整行像ngtable(angularjs)中的超链接(在新选项卡等中打开)一样
- azure - 在 AWS ECS 中部署时,Spring Boot 中的 Azure AD 集成不会重定向到 https
- python - 给定 TF2.1 中每一行的起始索引,如何对张量进行切片?
- php - 如何通过 WooCommerce 中的时间限制限制每个客户的订单数量
- c# - 实体框架中的关系(数据库优先)
- python - 毕达哥拉斯三元组与 python
- android - 如何在 Postman 中使用 API 的 Header 和 Request 参数查看响应
- python - 如何在 Python 中的 y 轴(垂直)上镜像/翻转字符串和/或整数?
- python - 如果我开始用损失函数的大值训练我的 keras 模型,这有关系吗