Background Task - Thread not working properly

Hi,

I’m using live ticker from kite and it is running whole day and i’ve python fastApi server which are having other apis as well.

the ticker process i started in background using backgroundtask
this is my code to start ticker process
@app.get(‘/my-ws’)
def init_ws(save:bool=False, background_tasks:BackgroundTasks= BackgroundTasks()):
print(save, “save”)
try:
background_tasks.add_task(start_ticker_threads, save)
return {“message”: “Ticker threads started”}
except Exception as e:
return {“error”: e}

And this is my ticker function
def start_ticker_threads(save):
try:
# DEFINE ALL THREADS
print(“START TICKER”)
thread1 = threading.Thread(target=ticker.initiatKiteTicker, args=[“T1”, (“NIFTY”, ), save])
thread2 = threading.Thread(target=ticker.initiatKiteTicker, args=[“T2”, (“BANKNIFTY”, “FINNIFTY”,), save])
thread3 = threading.Thread(target=ticker.initiatKiteTicker, args=[“T3”, (“SENSEX”, “MIDCPNIFTY”, “BANKEX”, ), save])
# Start threads
thread1.start()
time.sleep(0.5)
thread2.start()
time.sleep(0.5)
thread3.start()
subscribe_to_channel()
# Wait for threads to complete
thread1.join()
thread2.join()
thread3.join()
return ‘Initiated…’
except Exception as e:
return str(e)

i will have three thread to get data the live data from kite zerodha.

it is running one hour seamlessly but after an hour it start to send task in pending
Task <Task pending name=‘Task-235021’ coro=<WebSocket.send_json() running at /home/eulogik/.local/lib/python3.8/site-packages/starlette/websockets.py:173> cb=[run_until_complete..done_cb()]> got Future attached to a different loop exception to sent messsga Task <Task pending name=‘Task-235021’ coro=<WebSocket.send_json() running at /home/eulogik/.local/lib/python3.8/site-packages/starlette/websockets.py:173> cb=[run_until_complete..done_cb()]> got Future attached to a different loop

Also, the websocket from the client gets disconnected and my server slows down.

I don’t have much experience in python so can anybody please help me.

i’m using 4 core cpu.

Thanks in Advance