我想在 Python 中使用 Twilio 安排短信。在阅读了一些文章后,我开始了解 Celery。但我选择不使用 celery 并使用 Python Threading 模块。线程模块在使用一些虚拟函数时工作得很好,但是在调用时
client.api.account.messages.create(
to="+91xxxxxxxxx3",
from_=settings.TWILIO_CALLER_ID,
body=message)
它同时发送短信。
这是我的代码
from threading import Timer
from django.conf import settings
from twilio.rest import Client
account_sid = settings.TWILIO_ACCOUNT_SID
auth_token = settings.TWILIO_AUTH_TOKEN
message = to_do
client = Client(account_sid, auth_token)
run_at = user_given_time() #this function extracts the user given time from database. it works perfectly fine.
# find current DateTime
now = DT.now()
now = DT.strptime(str(now), '%Y-%m-%d %H:%M:%S.%f')
now = now.replace(microsecond=0)
delay = (run_at - now).total_seconds()
Timer(delay, client.api.account.messages.create(
to="+91xxxxxxxxx3",
from_=settings.TWILIO_CALLER_ID,
body=to_do)).start()
所以问题是 Twilio 同时发送短信,但我希望它在给定的延迟后发送。
您在启动 Timer之前调用该函数,然后将返回值传递给 Timer 线程。您需要向 Timer 传递函数client.api.account.messages.create
和 kwargs 以将其作为单独的参数传递,以便线程可以在时机成熟时调用函数本身:
Timer(delay, client.api.account.messages.create,
kwargs={'to': "+91xxxxxxxxx3",
'from_': settings.TWILIO_CALLER_ID,
'body'=to_do)).start()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句