How to Schedule SMS and Calls on Twilio
A very common use case for using a service like Twilio is to be able to schedule Calls or SMS's. Maybe you want to schedule a conference call, schedule a text to go out at specific time, or notify all your users about something via SMS every day. Twilio doesn't have scheduling built in, but here's an easy way to schedule your Twilio SMS's and Calls using IronWorker.
Note: All of the code in this post is available on Github and we recommend you clone that repo as a starting point rather than copying and pasting from this post. You will need to have an Iron.io account and a Twilio account to run the examples and this post is meant to quickly take you through the important things without going into setup/configuration which you can find on this README.
Create an SMS worker
First, let's start by creating a simple sms worker. You can write this in any language, but for this post, We'll be using Ruby. This worker simply sends an SMS via the Twilio API, but you can easily make it do a whole lot more like get data from various places and send a more meaningful message depending on what your application does. This is sms.rb:
Upload the worker
Ok, now that we have our worker code, we need to upload it and to do that we need a .worker file that defines our worker's dependencies. So we create a file called sms.worker:
Then we upload it:
> iron_worker upload sms
That will package and upload the sms worker to IronWorker.
Queue up tasks for the worker
Now that we've created our sms worker and uploaded it, we can queue up tasks for it. One task or millions of tasks, doesn't matter. We simply call our POST task endpoint, so in Ruby, that looks like this:
Queue up tasks to run in the future
Notice the :delay option we in the code sample above? That is the number of seconds the job will wait before it is executed. If you want to send a text in one hour from now:
Scheduling recurring texts or calls
We know how to schedule things to run a single time at some point in the future using the "delay" option, but how do we create a recurring schedule? It's easy, just change the tasks.create call to schedules.create and pass in the schedule:
That script will run every 24 hours.
Generally, a scheduled task will do more than send out a single SMS. A common use case is to iterate through all your users and queue up a task for each user to send them all a custom SMS. So you might have a "master" worker that queues up a bunch of "slave" tasks. Something like this:
So far it's been SMS examples, what about calls?
All of the above can be switched to calls by just switching from sending texts to making calls using Twilio call API:
So there you have it, you can now do all kinds of scheduling scenarios for SMS and phone calls with Twilio.
Start Building With Iron.io Today
Try all features right away.
Get Iron For Free
No credit card required.
Want Information on Professional and Enterprise Plans? Contact Us