python - Program that either waits for user input or runs at defined intervals? -
i have program runs @ regular intervals. right program runs continuously, checking new files every 30 minutes:
def filechecker(): #check new files in directory , stuff while true: filechecker() print '{} : sleeping...press ctrl+c stop.'.format(time.ctime()) time.sleep(1800) however, i'd user able come terminal , enter keystroke manually call filechecker() instead of either waiting program waking sleep or having relaunch program. possible do? tried @ using threading, couldn't figure out how wake computer sleep (don't have experience threading).
i know :
while true: filechecker() raw_input('press key continue') for full manual control, want have cake , eat too.
the solution provided clindseysmith introduces 1 more key press original question asking (at least, interpretation thereof). if want combine effect of 2 snippets of code in question, i.e., don't want have press ctrl+c calling file checker immediately, here's can do:
import time, threading def filechecker(): #check new files in directory , stuff print "{} : called!".format(time.ctime()) interval = 5 or 1800 t = none def schedule(): filechecker() global t t = threading.timer(interval, schedule) t.start() try: while true: schedule() print '{} : sleeping... press ctrl+c or enter!'.format(time.ctime()) = raw_input() t.cancel() except keyboardinterrupt: print '{} : stopped.'.format(time.ctime()) if t: t.cancel() the variable t holds id of thread scheduled next call file checker. pressing enter cancels t , reschedules. pressing ctrl-c cancels t , stops.
Comments
Post a Comment