bash - Python: How to resume excecution of Python script? -


i have following keeps checking current time in while loop, , when matches time_defined runs code in if statement.

also, suggestions of improvement welcome.

thank in advance!

any long-running python script (including yours) run while computer awake, pause execution while computer sleeps, automatically resume execution when computer wakes again. however, there couple of problems script may preventing running correctly, if computer sleeps through time specified in time_defined.

first, datetime.datetime.now() , datetime.datetime() have 1-microsecond precision. depending how fast loop runs, may not evaluate time_now = datetime.datetime.now() line during exact microsecond specified in time_defined (implicitly 20:00:00.000000). true if computer happens asleep during particular microsecond. in either of these cases, test never come out true, , script never emerge loop. fix both of these problems testing time_now >= time_defined instead of time_now == time_defined. there no way run scheduled code while computer sleeping. however, change, if computer sleeps through scheduled time, scheduled code run wakes up.

second, code using busy loop scheduling, inefficient. won't prevent running correctly, peg 1 core of processor @ 100% usage while running. if use time.sleep(), can reduce processor use zero. in principle, use time.sleep((time_defined-time_now).totalseconds()) sleep right number of seconds. however, (at least on mac) timer counts seconds during computer awake, suspending computer throw off schedule. however, use sequence of short sleeps (e.g., 1 second) improve efficiency dramatically , still have precise timekeeping.

here's code fixes both of these problems:

import datetime, time  def background_program():     time_defined = datetime.datetime(2017, 4, 7, 20, 0, 0)     ...      while(true):         time_now = datetime.datetime.now()          if time_now >= time_defined:             try:                 # run code                 pass             except:                 print('failed run')             finally:                 break         else:             # use shorter delay if want more exact runtime             time.sleep(1) 

here's more streamlined code same thing. i've added command line argument, can call python myscript.py --start-time 2017-04-17 20:00:00. (you can run python myscript.py --help little help.)

import datetime, time, argparse  def background_program(time_defined):      # wait until time_defined, sleeping in short steps     # note: use shorter delay more precision     print "waiting until {}".format(time_defined.strftime('%y-%m-%d %h:%m:%s'))     while(datetime.datetime.now() < time_defined):         time.sleep(1)      # perform scheduled action     try:         print('running scheduled task.')     except:         print('failed run')   if __name__ == '__main__':     parser = argparse.argumentparser(description='run background task.')     parser.add_argument(         '--start-time', nargs=2, default=none,         help='specify time run task, in yyyy-mm-dd hh-mm-ss format.'     )     args = parser.parse_args()     if args.start_time not none:         start_time = datetime.datetime.strptime(' '.join(args.start_time), '%y-%m-%d %h:%m:%s')         background_program(start_time) 

Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -