Home > front end >  how to stop function in python (telegram bot)
how to stop function in python (telegram bot)

Time:10-16

I try to make selenium bot that integrate to telegram so i can start and stop easily

def mulai(update, context):
    update.message.reply_text('Absen Start!')
    while True:
        if pycron.is_now('*/1 * * * *'):
            absen()
        time.sleep(60)

but how to stop it?

CodePudding user response:

To stop the code from running you can use the break statement in python.


from time import sleep

#Counting up to 10
for i in range(10):
    print(i 1)
    sleep(1)
    
    #stop counting at 5
    if i == 4:
        break

Without the break statement the code would continue counting up to 10.

CodePudding user response:

Based on clarification in comments, you are trying to stop one loop from elsewhere. One approach is a shared variable:

run_flag = True

def fn1():
    while run_flag:
        do_stuff()
        sleep(60)

def stop_fn1():
    global run_flag
    run_flag = False

This is safe so long as only one write access to run_flag can be made at any one time, i.e. you aren't trying to share it accross multiple threads. If you are you need to look at using something thread safe, like a semaphore.

There is no need for run_flag to be global, as long it is can be accessed by both the looping function and the function which sets it.

  • Related