Note: All of the code in this post is available on Github and I 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 workerFirst, let's start by creating a simple sms worker. You can write this in any language, but for this post, I'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 workerOk, 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 workerNow 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 futureNotice 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 callsWe 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:
ConclusionSo there you have it, you can now do all kinds of scheduling scenarios for SMS and phone calls with Twilio.
The full code and working examples for this are at: https://github.com/iron-io/iron_worker_examples/tree/master/ruby_ng/twilio_scheduling