Search code examples
pythonfunctionloopsif-statementschedule

Need to check if an event is already happened then exit the (endless) loop but the program must run continously


I'm trying to write a little program in Python to search some specific value inside a table on a webpage. Eventually I can get the value with a function called Alert_Red. I need to call the function automatically every 5 seconds but when I try the code below it gives me the correct values but in an endless loop.

[...some code above...]

def Alert_Red():
    if advColor == avc_red and delta <= fivesec_datetime:
        print('New RED advisory please check the following link: ', link)
        if advColor1 == avc_red and adv_datetime1 == adv_datetime:
            print('Another new RED advisory please check the following link: ', link)

schedule.every(5).seconds.do(Alert_Red)

while True:
    schedule.run_pending()
    time.sleep(1)

Output with the first "if clause" true:

New RED advisory please check the following link: , link
New RED advisory please check the following link: , link
New RED advisory please check the following link: , link
[endless loop every 5 sec]

Output with the second "if clause" true:

Another new RED advisory please check the following link: , link
Another new RED advisory please check the following link: , link
Another new RED advisory please check the following link: , link
[endless loop every 5 sec]

The program must run continously (even when the if clauses are true because i need to check them always) but I need to be advised only one time (the first time the values are found and/or if they change) and the Output i need is:

New RED advisory please check the following link: ', link

or for the second "if clause" true:

Another new RED advisory please check the following link: ', link

Solution

  • If I understand your problem, it can be solved with a global variable that tracks whether or not you have issued an advisory. Initialize this variable to False outside this function (somewhere in your start-up code).

    def Alert_Red():
        global advised
        if advColor == avc_red and delta <= fivesec_datetime:
            if not advised:
                print('New RED advisory please check the following link:', link)
                advised = True
            if advColor1 == avc_red and adv_datetime1 == adv_datetime:
                if not advised:
                    print('Another new RED advisory please check the following link: ', link)               
                    advised = True