我想在Python中使用Twilio来安排SMS。在阅读了一些文章后,我开始了解芹菜。但我选择不使用芹菜并使用Python线程模块。线程模块在使用某些虚拟函数时可以正常工作,但在调用时
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()
请参阅documentation for Timer并注意到需要将args
和kwargs
参数传递给提供的函数。
Timer
不应该与Web服务一起使用,原因如下:
因此我建议,使用一些任何队列来做这些事情。