0

I have this code:

def runner1():
    os.system('python something.py')
..... and so on
thread_run_1 = threading.Thread(target=runner1, args=[])
....
i =0 
j = 0
while i < 2: # i want to run continuously, dont want to use cron jobs 
    print "while 1"
    #i made it simpler, but here are a lot of checks
    while j == 0:
        print "while 2"
        thread_run_1.start()
        ......
        time.sleep(3600)
        break
    print "back to while 1"
    i+=1
    print i

It's possible to avoid this error: RuntimeError: threads can only be started once?

Bach
  • 6,145
  • 7
  • 36
  • 61
MikeT
  • 65
  • 7
  • Why not create a new thread? – bereal Jun 17 '14 at 08:36
  • @bereal True. But I wanted to know if its possible directly from code. – MikeT Jun 17 '14 at 08:39
  • 1
    What do you mean by "directly from code"? You would create a new thread directly from code. Python threads are thin wrappers around the OS threads, so when a thread is stopped, it no longer exists. Bereft of life, it rests in peace. It's an ex-thread. Start a new one. – bereal Jun 17 '14 at 08:45

2 Answers2

1

You can prevent this by checking via isAlive before instantiating the Thread object. Spelling will vary depending on version. Relevant doc here.

skytreader
  • 11,467
  • 7
  • 43
  • 61
1

Why are you trying to restart a thread ? Since the constructor will get worker argument, then it seems logical that that's the only thing that will ever run on that thread. If what you want to do is trigger the target to process another piece of info or just run the job again, you could :

a) Build another thread and run that (i don't know how expensive that is memory wise)

b) Make your target get a reference to a Queue object and pass information for processing into that from the main thread.

If you're trying to find something similar to java runnables or callables I don't think python offers such a construct

omu_negru
  • 4,642
  • 4
  • 27
  • 38