Wild_rasta
Wild_rasta

Reputation: 3

Starting loop at exact time in the hour - 12 options

I want that loop start at 00 min and 2 sec or 05 min and 2 sec or 10 min and 2 sec, etc...

I have code which work but i feel so stupid because i think this can be solved in a better way. not the gopnik style.

How can I do it?

def time_now():
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    print("Current Time =", current_time)


while True:
         
        now = datetime.now()
        while ( now.minute == 0 and now.second == 2) \
           or ( now.minute == 5 and now.second == 2) \
               or ( now.minute == 10 and now.second == 2) \
                   or ( now.minute == 15 and now.second == 2) \
                       or ( now.minute == 20 and now.second == 2) \
                           or ( now.minute == 25 and now.second == 2) \
                               or ( now.minute == 35 and now.second == 2) \
                                   or ( now.minute == 40 and now.second == 2) \
                                       or ( now.minute == 45 and now.second == 2) \
                                           or ( now.minute == 50 and now.second == 2) \
                                               or ( now.minute == 55 and now.second == 2):
            
            time_now()
            #print("Current Time =", current_time)
            print('Something')
            time.sleep(300)
        


Upvotes: 0

Views: 262

Answers (3)

Haukland
Haukland

Reputation: 755

You can use the modulus operator as all your time instances are divisible by 5:

while ( now.minute % 5 == 0 and now.second == 2):
    print('Something')
    time.sleep(300)

Upvotes: 3

Amiga500
Amiga500

Reputation: 1275

Why the second while loop? Do you want to freeze the machine* for that second - then why apply the time.sleep? Looks kinda superfluous.

*note machine in this instance = cpu core, not the interpreter. I'm also not sure if it will sleep you for 300 seconds or 300.999 seconds if that distinction is important.

Anyway, the mod approach will work fine given your params here, but is rather fixed to params always being compatible with modulus. Could try

while True:
     
    now = datetime.now()
    if ( now.minute in [0,5,10,15,20,25,30,35,40,45,50,55] and now.second == 2):
        #Do something
        pass

Upvotes: 1

Alexandru DuDu
Alexandru DuDu

Reputation: 1044

You can use cronjobs for this type of aproach. You can read and apply from here

Edited: For managing seconds, you can simply use sleep function in the cronjob

Upvotes: 0

Related Questions