0

I'm trying to run a method every minute.

The method does some operations on the internet so it might take anywhere from 1 second to 30 seconds.

What I want to do is calculate the time spent by this method and then sleep for the remaining time, to make sure that the method itself runs every minute.

Currently my code looks like this:

def do_operation():
    access_db()
    sleep(60)

As you can see this does not take into account the delay whatsoever, and although it works, it will at some point fail and skip a minute completely, which should never happen.

martineau
  • 119,623
  • 25
  • 170
  • 301
G. Ramistella
  • 1,327
  • 1
  • 9
  • 19
  • what is your problem exactly? you should know subtraction already so reading timestamp i.e. in seconds. milliseconds whatever before and after your method should be easy so would be the math you need to do – Marcin Orlowski May 05 '19 at 17:18
  • Possible duplicate of [What is the best way to repeatedly execute a function every x seconds in Python?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python) – marsnebulasoup May 05 '19 at 17:21

2 Answers2

1
import time

def do_operation():
    start = time.time()
    access_db()
    time.sleep(60-time.time()+start)
Steven Shi
  • 1,022
  • 1
  • 10
  • 10
0

This code will allow you to run a callable in defined intervals:

import time
import random

def recurring(interval, callable):
    i = 0
    start = time.time()
    while True:
        i += 1
        callable()
        remaining_delay = max(start + (i * interval) - time.time(), 0)
        time.sleep(remaining_delay)

def tick_delay():
    print('tick start')
    time.sleep(random.randrange(1, 4))
    print('tick end')

recurring(5, tick_delay)

Notes

  • The function tick_delay sleeps for some seconds to simulate a function which can take an undefined amount of time.
  • If the callable takes longer than the defined loop interval, the next iteration will be scheduled immediately after the last ended. To have the callable run in parallel you need to use threading or asyncio
Cloudomation
  • 1,597
  • 1
  • 6
  • 15