首页 > 解决方案 > 如何在计时器上运行一个函数,并选择在 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

标签: pythonpython-3.7

解决方案


您可以使用时间和 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
>>>

推荐阅读