如何使用Twilio使用Celery来安排短信?

问题描述 投票:0回答:2

我想在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同时发送短信,但我希望它在给定延迟后发送。

django python-3.x twilio
2个回答
3
投票

您在启动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并注意到需要将argskwargs参数传递给提供的函数。


0
投票

Timer不应该与Web服务一起使用,原因如下:

  1. Web请求使用多个线程提供。
  2. 您需要等待计时器线程执行,否则它将变为阻塞,否则将不会执行计时器线程。

因此我建议,使用一些任何队列来做这些事情。

© www.soinside.com 2019 - 2024. All rights reserved.