1

I have a small script that I have written to perform tasks every 5 minutes (this does not need to be exact), but as it is written currently the only way it can be cancelled is with Ctrl+Z (linux terminal) and there is no way of changing what set of tasks it performs without restarting the script.

As a result, I'd like to change the script to be able to accept user input while waiting to do the next run without interrupting the 5-minute timer by any large amount (as killing the script and restarting currently does), but I can't figure out how to get raw input to accept values for only a given time, etc. Also the current code is written in Python 2.7, but I'm happy to convert to 3 if that makes the solution easier.

The current code looks something like this:

# Setup for the tasks
while(True):
    # Do the tasks
    for i in range(5):
        print "Next run in " + str(5-i) + " mins"
        time.sleep(60)

Any ideas?

UPDATE: This question did not lead to a specific code solution being posted, so here'a a link to a later question that had a simple version of the solution I implemented (and the one simple edit that it required it to work in the answers)/

Community
  • 1
  • 1
DTR
  • 322
  • 5
  • 19
  • You are using an infinite loop, so exiting with ctrl+z is obvious, isn't it? Would you plz clearify your question? – Ahsanul Haque Aug 29 '15 at 12:36
  • @ThomasLee Thanks, I couldn't seem to find anything before but the solutions you linked to should work. – DTR Aug 29 '15 at 12:40
  • @AhsanulHaque Not really, it would be far better to have the program exit gracefully on a given user input (e.g. hitting enter on a blank line) than forcibly having to kill the process. Also I'd like to be able to enter input during the `wait` to change the set of tasks that the script performs on each iteration, as I mentioned in the question. – DTR Aug 29 '15 at 12:42
  • 1
    Note: Ctrl-Z in Bash does **not** kill the process - it suspends it and sends it to the background. You can see a list of currently suspended jobs with the `jobs` command, and resume execution of a suspended job with `fg` job_spec; if there's only one currently suspended job you can omit the job_spec number. Type `help jobs`, `help bg`, & `help bg` in the Bash shell for more info. – PM 2Ring Aug 29 '15 at 12:43
  • @PM2Ring Yeah, I was just typing quickly without thinking. It's good to be precise, though, so thanks for the correction. – DTR Aug 29 '15 at 12:53
  • @PM2Ring holy, I did **not** know that – xrisk Aug 29 '15 at 13:28

1 Answers1

1

I think you want something like that.

import threading

def takeInput():
    """This function will be executed via thread"""
    value = raw_input("what you want:")
    return

#initialize how you want
value = 0 
t = threading.Thread(target=takeInput)
t.start()
time.sleep(5) 
Ahsanul Haque
  • 9,145
  • 2
  • 27
  • 48