如何启动另一个线程而不等待函数完成?



嘿,我正在制作一个电报机器人,我需要它能够一次多次运行相同的命令。

dispatcher.add_handler(CommandHandler("send", send))

这是命令^

在命令里面,它启动了一个函数:

sendmail(email, amount, update, context)

此函数大约需要5秒才能完成。我想要它,这样我就可以一次运行它多次,而不需要等待它完成。我尝试了以下操作:

Thread(target=sendmail(email, amount, update, context)).start()

这将给我没有错误,但它等待函数完成,然后继续。我也试过这个

with ThreadPoolExecutor(max_workers=100) as executor:
executor.submit(sendmail, email, amount, update, context).result()

但是它给了我以下错误:

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

这是我第一次尝试线程,但也许可以试试这个:

import threading
x1 = threading.Thread(target=sendmail, args=(email, amount, update, context))
x1.start()

你可以把x1 = threading...x1.start()放在一个循环中,让它运行多次

希望有帮助

它不是等待一个函数完成,然后启动另一个函数,而是在python中GIL(全局解释器锁)在给定的时间只执行一个线程。由于线程使用多个内核,在大多数情况下,两个函数之间的时间可以忽略不计。

下面是使用ThreadPoolExecutor启动线程的方法,请根据您的使用情况进行调整。

def async_send_email(emails_to_send):
with ThreadPoolExecutor(max_workers=32) as executor:
futures = [
executor.submit(
send_email,
email=email_to_send.email,
amount=email_to_send.amount,
update=email_to_send.update,
context=email_to_send.context
)
for email_to_send in emails_to_send
]
for future, email_to_send in zip(futures, emails_to_send):
try:
future.result()
except Exception as e:
# Handle the exceptions.
continue
def send_email(email, amount, update, context):
# do what you want here.

最新更新