A
A
Andrey Romanov2021-10-22 11:22:03
Python
Andrey Romanov, 2021-10-22 11:22:03

How to run a method every minute?

Good day. Tell me, how can I run a method (function) in my program every minute?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-10-22
@roni43

The answer depends on a number of factors.
1. Should the program do something else? If yes, what exactly?
2. How many such periodic methods will exist? Strictly one, or maybe more? Should they have different periods?
If the program is synchronous, and there is only one method, then a simple trick can be used:

import time

stop = False
def proc_to_call():
  global stop
  #Это твой периодический вызов
  #когда нужен останов, делаешь stop = True
  pass

while not stop:
  time.sleep(60)
  proc_to_call()
#код после цикла выполнится только после прерывания цикла.

If there are several calls and at different intervals, then it is better to use the schedule package . But you will still have an infinite loop like
while True:
    schedule.run_pending()
    time.sleep(1)

And while the program is spinning in this cycle, it will not do anything else.
If you need to do something in parallel with a periodic call, then things get more complicated.
If your program is synchronous, then you will need a separate thread of execution .
import threading

class MyJob(threading.Thread):
  def __init__(self):
    super().__init__(self)
    self.stop = threading.Event()

  def proc_to_call(self):
    #Это твой периодический вызов
    pass
  
  def run(self):
    while not self.stop.wait(60):
      self.proc_to_call()

job = MyJob()
job.start()
#код основного потока продолжает выполняться после этого
#когда нужен останов, делаешь 
job.stop.set() #сигналим об останове
job.join() #ждём завершения потока

Why use Event instead of simple boolean variable and time.sleep()? Because with time.sleep() you have to wait until the end of the minute before the thread checks the boolean flag again and knows it's time to stop. And when using Event, setting it will immediately interrupt the wait - and exit the loop.
And if your program is asynchronous, then everything is simplified, since coroutines can already alternate their execution, executing "as if in parallel". You can use both schedule and simple loop, just remember to use await asyncio.sleep() instead of time.sleep().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question