A program that either waits for user input, or runs at regular intervals?

I currently have a program that runs at regular intervals. Right now, the program runs continuously, checking for new files every 30 minutes:

def filechecker():
    #check for new files in a directory and do stuff

while True:
    filechecker()
    print '{} : Sleeping...press Ctrl+C to stop.'.format(time.ctime())
    time.sleep(1800)

However, I would also like the user to be able to come to the terminal and enter a keystroke manually to call the filechecker () file instead of waiting for the program to wake up or restart the program. Is it possible to do this? I tried to look at the use of threads, but I could not figure out how to wake a computer from sleep (not much experience with threads).

I know that I could just as easily:

while True:
    filechecker()
    raw_input('Press any key to continue')

for full manual control, but I want me to have my cake and eat it too.

+4
3

, clindseysmith, , , ( , ). , .. Ctrl + C , :

import time, threading

def filechecker():
    #check for new files in a directory and do 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())
        i = raw_input()
        t.cancel()
except KeyboardInterrupt:
    print '{} : Stopped.'.format(time.ctime())
    if t: t.cancel()

t , . "Enter" t . Ctrl-C t .

+3

try/except KeyboardInterrupt ( , Ctrl-C, time.sleep(). , . :

while True:
    filechecker()
    try:
        print '{0} : Sleeping...press Ctrl+C to stop.'.format(time.ctime())
        time.sleep(10)
    except KeyboardInterrupt:
        input = raw_input('Got keyboard interrupt, to exit press Q, to run, press anything else\n')
        if input.lower() == 'q':
            break
+4

You can do this so that pressing ctrl + c filechecker()does this:

def filechecker():
    #check for new files in a directory and do stuff

filechecker()
while True:
    print '{} : Sleeping...press Ctrl+C to run manually.'.format(time.ctime())
    try:
        time.sleep(1800)
    except KeyboardInterrupt:
        filechecker()
   filechecker()
0
source

Source: https://habr.com/ru/post/1584574/


All Articles