0

from Make 2 functions run at the same time by using thread. It can make two function with the same time. Is it possible to call function with thread in try except block?

import threading
from threading import Thread
import time

def queryRepeatedly():
    while True:
        while True:
            try:
                Thread(target = foo).start()
                Thread(target = bar).start()
                print ''
            except:
                continue
            else:
                break

def foo():
      print 'foo'
      time.sleep(1)
def bar():
      print 'bar'
      time.sleep(3)

queryRepeatedly()

This my code not work,i need to run two function separately with try except block. what should i do?

Thanawat.ch
  • 25
  • 1
  • 2
  • 7
  • could you explain why do you have two while True ? Also, what errors are you trying to catch ? Do you have a traceback ? – madjaoue Jul 03 '18 at 09:51
  • am following [Restarting a program after exception](https://stackoverflow.com/questions/17533104/restarting-a-program-after-exception) it can merge two loop into one. I have two function, first is write data to Database(Influxdb) and second is query data from database. I need to catch error time out of first function. – Thanawat.ch Jul 03 '18 at 10:10
  • Is your problem solved ? – madjaoue Jul 10 '18 at 10:14
  • 1
    Sorry for late, i just tried it this moning. and it's work for me, Thank you very much.@Mium – Thanawat.ch Jul 12 '18 at 07:15

1 Answers1

0

I think this might be what you're looking for:

import threading
from threading import Thread
import time

def queryRepeatedly():
   Thread(target = foo).start()
   Thread(target = bar).start()

def foo():
    while True:
        try:
            print 'foo'
        except : #catch your error here
           pass # handle your error here
        finally:
           time.sleep(1)
def bar():
    While True:
        try:
           print 'bar'
        except : #catch your error here
           pass # handle your error here
        finally:
           time.sleep(3)

queryRepeatedly()
madjaoue
  • 5,104
  • 2
  • 19
  • 31