-1

I want to execute a function repeatedly every 5 seconds and at the same time take input from the user and based on the input stop the execution? Ex:

def printit():
   t=threading.Timer(3.0,printit)
   t.start()
   n=str(input())
   if(n=='rajesh'):
        t.cancel()
   else:
      #I want to continue the execution here
Rajesh s
  • 175
  • 1
  • 8
  • Stopping a thread: https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python – blhsing Jun 22 '18 at 04:03
  • What's the problem you're trying to solve with what you have here? Honestly, I wouldn't bother with threads and would just loop around `time.sleep(last+5s - now)`, but this should work. – abarnert Jun 22 '18 at 04:13

3 Answers3

1

This Should Help

import time
#use a While loop
While True:
      #request said user input
      x= input("Please Press 1 to continue Or 2 to Exit")
      #then an if statement 
      if x==1:
            #call your function
            printit()
            time.sleep(5)
      else:break

This should Do the trick

One Love
  • 11
  • 1
  • 3
1

If you really want to use threading, then this should work:

import threading
import time

def worker():
    while True:
        user_input = input("Enter text:")
        if user_input == 'rajesh':
            break
        else:
            time.sleep(5)

thread = threading.Thread(target=worker, daemon=True)
thread.start()
thread.join()
hoploop
  • 44
  • 2
-2

This Should Help

#request said user input
x= input("Please Press 1 to continue Or 2 to Exit")
#use a While loop
While True:
      #then an if statement 
      if x==1:
            #call your function
            printit()
      else:break

This should Do the trick

One Love
  • 11
  • 1
  • 3