Hey I am making a telegram bot and I need it to be able to run the same command multiple times at once.
dispatcher.add_handler(CommandHandler("send", send))
This is the command ^
And inside the command it starts a function:
sendmail(email, amount, update, context)
This function takes around 5seconds to finish. I want it so I can run it multiple times at once without needing to wait for it to finish. I tried the following:
Thread(target=sendmail(email, amount, update, context)).start()
This would give me no errors but It waits for function to finish then proceeds. I also tried this
with ThreadPoolExecutor(max_workers=100) as executor:
executor.submit(sendmail, email, amount, update, context).result()
but it gave me the following error:
No error handlers are registered, logging exception.
Traceback (most recent call last):
File "C:UserssealAppDataLocalProgramsPythonPython310libsite-packagestelegramextdispatcher.py", line 557, in process_update
handler.handle_update(update, self, check, context)
File "C:UserssealAppDataLocalProgramsPythonPython310libsite-packagestelegramexthandler.py", line 199, in handle_update
return self.callback(update, context)
File "c:UserssealDownloadstelegrambotmain.py", line 382, in sendmailcmd
executor.submit(sendmail, email, amount, update, context).result()
File "C:UsersmainAppDataLocalProgramsPythonPython310libconcurrentfuturesthread.py", line 169, in submit
raise RuntimeError('cannot schedule new futures after '
RuntimeError: cannot schedule new futures after interpreter shutdown
2
Answers
This is my first attempt at threading, but maybe try this:
You can just put the
x1 = threading...
andx1.start()
in a loop to have it run multiple timesHope this helps
It’s not waiting for one function to finish, to start another, but in python GIL (Global Interpreter Lock) executes only one thread at a given time. Since thread use multiple cores, time between two functions are negligible in most cases.
Following is the way to start threads with the ThreadPoolExecutor, please adjust it to your usecase.