linux - Scheduling a Python program to sleep within a given time period -


while true:       = datetime.datetime.now();       if now.hour >= 22 , now.hour < 3:          print "sleep"          sleep_at = datetime.datetime.combine(datetime.date.today(),datetime.time(3))          sleep_til = (sleep_at - now).seconds          print sleep_til          time.sleep(sleep_til)          print "wake"       else:          print "break"          break 

this code should make entire program go sleep @ 10 pm , wake @ 3 am. question is.. work? tried running it.. cannot change system/computer time.. cannot check. reason why posting question because coding using datetime.date.tday , datetime.datetime calling current date..

once again.. want program run before 10pm , sleep between 10pm 3am , rerun after 3am..

can check if right way it?

consider (extra-verbose clarity):

import time, datetime  # create time bounds -- program should run between run_lb , run_ub run_lb = datetime.time(hour=22)     # 10pm run_ub = datetime.time(hour=3)      #  3am  # helper function determine whether should running def should_run():     # current time     ct = datetime.datetime.now().time()     # compare current time run bounds     lbok = run_lb <= ct     ubok = run_ub >= ct     # if bounds wrap 24-hour day, use different check logic     if run_lb > run_ub:         return lbok or ubok     else:         return lbok , ubok   # helper function determine how far run_lb def get_wait_secs():     # current datetime     cd = datetime.datetime.now()     # create datetime *today's* run_lb     ld = datetime.datetime.combine(datetime.date.today(), run_lb)     # create timedelta time until *today's* run_lb     td = ld - cd     # ignore td days (may negative), return td.seconds (always positive)     return td.seconds   while true:     if should_run():         print("--do something--")     else:         wait_secs = get_wait_secs()         print("sleeping %d seconds..." % wait_secs)         time.sleep(wait_secs) 

but agree sleeping not best way delay program starting. may task scheduler on windows or cron on linux.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -