简体   繁体   中英

how to stop function in python (telegram bot)

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?

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.

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM