Home > Software design >  Check a condition every 3 minutes without functions and without interrupting the loop
Check a condition every 3 minutes without functions and without interrupting the loop

Time:03-28

I have this working code that checks a conditions every 3 minutes considering the local time, so every 0, 3, 6, 9.....It prints "checking condition".

import time
def get_next_time():
    minute = time.localtime().tm_min
    result = 3 - (minute % 3)   minute
    if result == 60:
         result = 0
    return result

next_run = get_next_time()

while True:

   now = time.localtime()

   if next_run == now.tm_min:
       print("checking condition")
       #some condition

       next_run = get_next_time()
   time.sleep(1)

The problem is that I need the code without functions, so I need to find a way to write this code without using any funcion, and I cannot use break or interrput the loop

I tried:

while True:

   minute = time.localtime().tm_min
   result = 3 - (minute % 3)   minute
   if result == 60:
       result = 0


   now = time.localtime()
   if result == now.tm_min:
       print("checking conditions")

   time.sleep(1)

But it does not work: it does not do nothing. Any ideas?

CodePudding user response:

you can compact the function in one statement:

import time

next_run = (3 - (time.localtime().tm_min % 3)   time.localtime().tm_min)`

while True:
    now = time.localtime()

    if next_run == now.tm_min:
        print("checking condition")
        #checking conditions...

        next_run=(3 - (time.localtime().tm_min % 3)   time.localtime().tm_min)`
    time.sleep(1)

CodePudding user response:

The first time, the get_next_time() will only be executed when next_run == now.tm_min. The second time, you execute it each loop

import time

minute = time.localtime().tm_min
result = 3 - (minute % 3)   minute
if result == 60:
    result = 0

while True:

   now = time.localtime()
   if result == now.tm_min:
       print("checking conditions")
       minute = time.localtime().tm_min
       result = 3 - (minute % 3)   minute
       if result == 60:
           result = 0

   time.sleep(1)

CodePudding user response:

Rounding to the next multiple of 3 minutes contradicts the specification "every 0...".

It is enough to do

import time

first= True       
while True:
    minute= time.localtime().tm_min
    if first or minute == target:
        print("checking condition")
        first= False
        target= (minute   3) % 60
    time.sleep(1)

Update:

I modified the code so that a single call to localtime is made on every iteration, to make fully sure that the minutes do not change between the calls.

More compact but less efficient:

import time

while True:
    minute= time.localtime().tm_min
    if 'target' not in locals() or minute == target:
        print("checking condition")
        target= (minute   3) % 60
    time.sleep(1)
  • Related