'How do I run a function every four minutes since a specific epoch?
My main function calls a number of subroutines in a while True: loop.
I want to add another function g() that only runs once every four minutes. Function g() should only run at 4 minutes, 8 minutes, 12 minutes, etc
I know I can check if a single amount of time has passed with if epoch >= x
But how do I run only g() every four minutes?
def main():
epoch = time.time()
count = 0
while True:
count = count + 1
if a() == 1:
b()
c()
d()
if count % 20:
e()
else:
f()
e()
if epoch >= 240:
g()
Edit; I can't run this as a separate thread as the answer in the duplicate suggested.
Solution 1:[1]
Create a new variable to store the next time the function should run:
import time
def main():
epoch = time.time()
count = 0
next_g = 0
while True:
count = count + 1
if a() == 1:
b()
c()
d()
if count % 20:
e()
else:
f()
e()
if (epoch := time.time()) >= next_g:
g()
next_g = epoch + 240
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bharel |
