Home > Net >  Python how to start 2 timers in the program
Python how to start 2 timers in the program

Time:04-21

I have a program with a bot, which during the working time should also save a list of orders every 10 minutes, as well as save logs every 1 minute. Part of the code is as follows:

timer1 = threading.Timer(600, save_orders_list)
timer2 = threading.Timer(60, save_log)
bot.infinity_polling(timeout = 10, long_polling_timeout = 5)

timer1.start()
timer1.join()
timer2.start()
timer2.join()
time.sleep(57600)

Here it was advised to add join() to each timer, but still the save functions are performed correctly separately from the timers.

What can be done in this case?

CodePudding user response:

There are multiple options to achieve what you are willing to, the very basic example is by using recursion & sleep function e.g.

import sched, time

def save_log():
    #your code to save logs
    time.sleep(60) # 1 min
    save_log() #after waiting for 1 min call the function again to save logs

Or you can use infinite loop with time function

while True:
    save_log()
    time.sleep(60) #wait for 1 min before next iteration

The above two approaches are not the neat way to achieve goal, other option which is neat as well as yet more advance way to handle this use case is following

s = sched.scheduler(time.time, time.sleep) #define a scheduler
def save_log(sc):
    #your code to save log
    sc.enter(60, 1, save_log, (sc,)) #schedule the next execution 1 min

s.enter(60, 1, save_log, (s,)) #Set first time schedule, 1 min
s.run()

You can check some more schedulers to meet your requirements from python official documentation here

  • Related