SMSGatewayCenter Blog

Building Recurring SMS in Your Own Scheduler: Anchored Dates, Occurrence Keys and Missed Runs

Recurring SMS looks like a cron line until a month ends on the 31st, a server sleeps through a run, or someone edits the schedule at 08:59. Here's how to build recurrence that never drifts, never double sends and always knows what to do when it's late.

Featured image for Building Recurring SMS in Your Own Scheduler: Anchored Dates, Occurrence Keys and Missed Runs
Abstract teal calendar dial with evenly spaced blue ticks and two orange displaced ticks, feeding a straight line of identical message blocks.
A recurring schedule is a promise made once and kept hundreds of times. The hard part is the handful of dates that don’t line up.

Table of Contents

  1. The Short Answer
  2. TL;DR
  3. Portal Recurring SMS or Your Own Engine
  4. Three Objects: Rule, Occurrence, Send
  5. Anchor Every Date to the Start
  6. Month Ends, Leap Days and Other Calendar Edges
  7. Time Zones and Recipients Abroad
  8. Occurrence Keys and the Double Send
  9. Missed Runs: Skip, Latest or All
  10. Quiet Hours and the Promotional Window
  11. Editing, Pausing and Ending a Rule
  12. Checks Before Every Run
  13. The 90-Day Header Trap
  14. Forecasting What a Rule Will Cost
  15. The Schema
  16. The Engine in Python
  17. Handing a Run to SMSApi/send
  18. Testing a Year of Schedules in a Second
  19. Decision Matrix
  20. Before You Go Live
  21. Unspecified Behaviour and How to Code Around It
  22. FAQs

The Short Answer

If you need recurring SMS driven from your own code, you build the recurrence yourself and call SMSApi/send when each run is due. The portal’s Recurring SMS feature is set up and managed in the dashboard and isn’t exposed through the API, so an app that creates, edits or pauses schedules for its users needs its own engine.

That engine is small, but four decisions make or break it.

First, compute every date from the start date, never from the last run. A monthly rule that starts on 31 January should land on 28 February, 31 March and 30 April. Chain it from the previous run and it drifts to the 28th forever.

Second, give every run a key made of the rule ID and the local date (r42:2027-03-31), and every recipient a key derived from that. Then a crash, a retry or an edit at 08:59 can’t send anything twice.

Third, decide per rule what happens when a run is late: skip it, send only the newest, or send every missed one. A bill reminder and a monthly statement want different answers.

Fourth, check the things that go stale between runs: balance, DLT template, sender ID, consent. And watch the calendar for the one trap that’s specific to India: a DLT header that sends nothing for 90 days is deactivated, so a quarterly or yearly rule on its own header can switch itself off.

The rest of this page is the design, the schema and a tested Python engine you can lift.

TL;DR

QuestionAnswer
Can I create or edit portal Recurring SMS campaigns over the API?No. Recurring SMS is a dashboard feature. Build your own engine and send each run through SMSApi/send.
How should I calculate the next date?From the anchor (start date) plus n intervals. Never from the previous run.
What about the 31st?Clamp to the month’s last day (Feb 28, Apr 30) or skip short months. Pick one per rule and store it.
What’s the duplicate protection?Occurrence key rule_id:local_date, recipient key hash(occurrence_key, recipient), both UNIQUE.
What if the server was down at 09:00?Your catch-up policy decides: skip, latest or all, with a maximum lateness per rule.
What about pauses?Resuming sets not_before. Dates missed during the pause are skipped, not replayed in a burst.
Time zones?Store an IANA zone with the rule. India has no DST, but recipients abroad might, and 09:00 New York moves by an hour in UTC across a DST change.
How many times does a weekly rule run in a year?Count it. A Friday rule that starts on 1 January 2027 runs 53 times in 2027, not 52.
What goes stale between runs?Balance, template status, sender ID status, consent and the audience itself. Check them on every run.
Anything India-specific?A DLT header unused for 90 days is deactivated. Quarterly rules from 1 December have gaps of 90 to 92 days.

Portal Recurring SMS or Your Own Engine

Start by checking whether you need to build anything. If a person in your team sets up a monthly reminder for a fixed group and checks the report afterwards, the dashboard feature does the job. Here’s what it gives you, going by the platform’s own help pages:

FeaturePortal Recurring SMS
Where you set it upRecurring SMS under the SMS compose menu in the dashboard
FrequencyAn interval from 1 to 999 and a unit of Days, Weeks, Months or Years (frequency guide)
Start and endStart date can’t be in the past, end date optional, trigger time as HH:MM (start and end dates)
Timing precisionDue campaigns are checked every few minutes, so a run can go out 5 to 10 minutes after its time
RecipientsBatch numbers or contact groups
PauseDisable and Enable; a resumed campaign carries on from its next trigger date (pausing)
EditsApply to future runs; a frequency change recalculates the next trigger from the last execution plus the new frequency (editing a running campaign)
A failed runCarries on at the next scheduled execution (fixing a failed campaign)
ReportsPer execution: SUCCESS, FAILED or PARTIAL, with counts, credits and a transaction ID (execution reports)

That covers a lot of ordinary use. The Recurring SMS guide walks through it for marketers.

You need your own engine when any of these is true:

  • Your users create the schedules. A SaaS app where each customer sets “remind my clients every month” can’t send its users to your SMS dashboard.
  • The audience is a query, not a list. “Everyone whose invoice is unpaid on the day” changes every run. A group you upload once doesn’t.
  • The text depends on the day. Amount due, next appointment, points balance. You need to render it at run time.
  • You need the schedule in your own data. Reporting, audit, a “next send” column in your admin screen, or a rule that has to stop the moment a contract ends.
  • You want WhatsApp, RCS or Telegram on the same schedule. The engine below doesn’t care which channel the send step calls.

Building it yourself costs you one thing the portal gives for free: if your scheduler is down at 09:00, nothing goes out at 09:00. The scheduling guide covers a hybrid where your database is the master copy and SMS gets handed to the platform with scheduleTime a little before it’s due. That works for recurrence too, and we’ll come back to it in the sending section.


Three Objects: Rule, Occurrence, Send

Keep three different things in three different places:

The rule is the promise: “on the 31st, at 09:00 India time, every month, until the contract ends”. It has a start date (the anchor), a local time, a zone, an interval and unit, an end condition, and the policies this page is about. When someone edits it, you write a new version instead of changing the old one.

The occurrence is one keeping of the promise: “the run for 2027-03-31”. It’s created when it becomes due, it has a key, a due time in UTC, and a state. It’s what you report on (“March’s reminder went out at 09:02, 4,812 accepted, 3 rejected”).

The send is one message to one person within one occurrence. It has its own key, the provider’s transaction ID, and whatever the delivery report says later.

Three panels, Rule, Occurrence and Send, connected by arrows, listing what each holds: anchor and policies on the rule, a date-based key and lease on the occurrence, and per-recipient keys and transaction IDs on the send, with three banners about edits, pauses and lateness.
Each layer can be retried without repeating the one before it. That’s the whole point of splitting them.

Why bother? Because each layer fails differently. A rule gets edited. An occurrence gets claimed by a worker that then dies. A send times out halfway through a list of five thousand numbers. If each has its own key and state, you can retry any one of them safely. If they’re one row with a last_sent_at column, every retry is a guess.


Anchor Every Date to the Start

Here’s the recurrence bug to design out first. The scheduler sends a run, then sets next_run = last_run + 1 month. That looks fine until the rule starts on the 31st.

Take a monthly rule that starts on 31 January 2027. If your month-adding function clamps, as many do, “31 January plus a month” becomes 28 February, which is right. But then the next run is “28 February plus a month”, which is 28 March. And it stays on the 28th forever.

RunAnchored (start + n months)Chained (last run + 1 month)
12027-01-312027-01-31
22027-02-282027-02-28
32027-03-312027-03-28
42027-04-302027-04-28
52027-05-312027-05-28
62027-06-302027-06-28

The fix is to stop asking “what comes after the last run” and start asking “what’s run number n”. Run n is the anchor plus n times the interval, computed fresh every time. The anchor never changes, so a short month can’t leak into the months after it.

This also makes your scheduler stateless about dates. You never store “next run” as the source of truth. You store the rule, and you compute. If you want a “next send” column for your admin screen, compute it and cache it, but don’t let the cache drive sending.

The same reasoning tells you how to read the portal’s edit behaviour. Its help page says a frequency change “recalculates next trigger date” from the “last execution + new frequency”. That’s chaining, and it’s a sensible way to handle an edit by hand. In your own engine you can do better: an edit creates a new rule version with a new anchor, and the dates from then on are computed from that anchor.


Month Ends, Leap Days and Other Calendar Edges

Anchoring fixes drift. It doesn’t decide what the 31st means in a 30-day month. You still have to choose.

Clamp moves a missing day to the last day of the month. 31 January gives 28 February, 31 March, 30 April. This is what people usually mean by “monthly on the 31st”, and it’s the right default for bills and statements.

Skip leaves out any month that doesn’t have the day. 31 January gives 31 March, 31 May, 31 July. This is how iCalendar works: RFC 5545 says a recurrence that produces an invalid date, such as 30 February, is ignored and not counted. It’s the right choice when the date itself matters more than the month, which is rare for messaging.

If you choose skip, decide how count works with it. Following the RFC, a skipped month doesn’t count toward “send 12 times”. So a skip rule on the 31st with a count of 3 sends on 31 January, 31 March and 31 May.

Leap days are the same problem once a year. A yearly rule anchored on 29 February 2028 lands on 28 February in 2029, 2030 and 2031 if you clamp, and on 29 February again in 2032. If you skip, it sends once every four years, which is almost never what a birthday message wants.

The end date needs one decision too: is until inclusive? Make it inclusive and say so in the UI. “Until 15 January” with weekly runs from 1 January should send on the 1st, the 8th and the 15th. People read it that way, and so does the portal’s help (“Campaign automatically stops after this date”).

Days of the week aren’t something an interval-and-unit rule handles. “Every 7 days” from a Friday stays on Fridays, which is fine. “The first Monday of every month” or “the last working day” needs a richer rule. If you need those, adopt RRULE from RFC 5545 rather than inventing your own syntax, and use a library that implements it. Keep the anchored-computation property either way.

One more thing that trips up budgets: count the runs, don’t assume them. A weekly rule starting Friday 1 January 2027 runs 53 times in 2027, because 2027 has 53 Fridays. The usual shortcut of “52 times a year” is off by one in that year, and that’s a whole extra send to every recipient.


Time Zones and Recipients Abroad

Store a time zone with every rule, by IANA name (Asia/Kolkata, Europe/London, America/New_York). Don’t store a fixed offset like +05:30. An offset is a fact about one instant; a zone is a rule about every instant.

For Indian recipients this is easy, because India doesn’t use daylight saving. 09:00 in Asia/Kolkata is always 03:30 UTC.

For recipients abroad it isn’t. Take a weekly 09:00 rule for New York. On Thursday 29 October 2026 that’s 13:00 UTC (18:30 in India). The US clocks go back on 1 November. On Thursday 5 November it’s 14:00 UTC (19:30 in India). Same wall-clock time for the person reading the message, a different instant for your scheduler.

So compute the due instant from the local date, the local time and the zone, every time, the same way you compute the date from the anchor. Never compute it by adding seven days’ worth of seconds to last week’s instant.

There’s one odd case: a local time that doesn’t exist. When clocks go forward, 02:30 is skipped. RFC 5545 says to drop such an instance. For messaging, dropping a run because of a clock change is worse than sending it an hour late, so the engine below sends it at the first valid instant after the gap (03:30 local). Nobody schedules reminders at 02:30, so you’re unlikely to see it, but your code should do something deliberate.

There’s a second clock involved too: the platform’s. When you send each run yourself, the moment of the API call is the send time, so the platform’s zone doesn’t matter. If you hand SMS runs to the platform with scheduleTime, it does matter, because that parameter takes a plain YYYY-MM-DD HH:MM:SS with no offset. The scheduling guide has a one-booking probe that pins it down. Run it before you hand anything over.


Occurrence Keys and the Double Send

A recurring sender has more ways to send twice than a one-off sender, because it runs again and again and it’s usually driven by a timer. Two workers wake up at the same minute. A deploy restarts a worker halfway through a run. Someone edits the time from 09:00 to 09:30 at 09:10, after the 09:00 run already went out.

Two keys handle all of that.

The occurrence key is the rule ID plus the local date: r42:2027-03-31. Not the rule version, not the time, not the run number. Insert occurrences with that key as the primary key, and a second worker that computes the same occurrence gets a conflict instead of a second run.

Leaving the version and the time out is what makes edits safe. Say the rule sends at 09:00 and someone moves it to 18:00 at 10:00 the same day. The new version computes today’s occurrence as r42:2027-03-31 at 18:00. That key already exists and is marked sent, so nothing happens until tomorrow. If you’d keyed on the time, or on the version, today would get a second message at 18:00.

There’s a trade-off: with date keys, a rule can’t send twice on the same local date. For daily, weekly, monthly and yearly rules that’s exactly what you want. If you ever need “every 6 hours”, key on the local date and hour instead, and keep the same idea: the key names the slot, not the attempt.

Using the run number as the key looks tempting, but it breaks on edits. Change the anchor and run number 4 means a different date. Dates don’t move.

The send key is a hash of the occurrence key and the recipient. hash("r42:2027-03-31" + "|" + "919999999999"). Insert one row per recipient before you send anything, with that key as the primary key. A worker that restarts finds the rows already there, sends only those still queued, and never touches the ones already accepted.

This is the idempotency pattern applied to a schedule. The schedule just gives you a natural, stable key that a one-off send doesn’t have. Keep the provider’s transactionId on the send row as text. It can be nineteen digits, and the lossless JSON guide shows what a float does to that.

Claiming an occurrence needs a lease, not a flag. A worker sets state = 'claimed', claimed_by, and claimed_until = now + 5 minutes, and keeps extending it while it works. If it dies, the lease runs out and another worker picks the occurrence up. Because the send rows are keyed, the second worker only sends what the first didn’t. In Postgres, claim with FOR UPDATE SKIP LOCKED so workers never wait on each other.


Missed Runs: Skip, Latest or All

Your scheduler will be down at some point when a run is due. A deploy, a database failover, a laptop-hosted cron job that went to sleep. When it comes back, there may be one or several runs in the past. What to do with them isn’t a technical question. It depends on the message, so make it a field on the rule.

Three policies cover nearly everything:

skip sends a missed run only if it’s still fresh, meaning no later than the rule’s max_late. Anything older is marked skipped with a reason. Use it for anything that’s about “now”: offers, digests, reminders for an event that has passed. A “sale ends tonight” message at 03:00 the next morning is worse than no message.

latest sends only the newest due run, however late, and skips the older ones. Use it when one message covers the state: “your bill of INR 2,340 is due on the 5th”. If three monthly reminders were missed, the customer needs the current one, not three.

all sends every missed run in order. Use it when each run is a record in its own right, like a monthly statement or a compliance notice that must exist for each period. Usually you’d also want a person to look at a backlog that large before it goes.

max_late is the other half. A bill reminder can be useful until the due date. An offer is stale in two hours. A birthday message is fine any time that day and wrong the next. Store it per rule.

A table of five recurring message kinds, bill reminder, account statement, offer, renewal notice and birthday wish, against missed-run policy, maximum lateness, month-end handling, longest gap between sends and header plan, with banners on anchored dates and the 90-day header gap.
Catch-up, lateness and calendar rules belong to the message, so they live on the rule.

The portal’s help says a failed recurring run “will retry on next scheduled execution”. In other words, the missed one isn’t replayed; the next one goes out as normal. That’s skip with no lateness allowance. It’s a safe default for a dashboard tool. Your own engine can be more precise per rule.

Whatever you choose, record skipped runs as rows with state = 'skipped' and a reason. “Skipped: 14 hours late, policy skip, max_late 2 hours” is an answer you can give a customer. A run that silently never happened isn’t.

And alert on it. One skipped run is a fact. Two skipped runs across different rules in an hour means your scheduler was down and you should know before your customers do. The observability guide covers the rest of that alerting.


Quiet Hours and the Promotional Window

Recurring promotional SMS in India meets the same posting window as any other promotional SMS. The platform’s Store and Forward OWH announcement puts the allowed window at “typically 10 AM to 9 PM as per TRAI guidelines”, and with Store and Forward OWH switched on, a promotional message sent outside the window is queued until it reopens. Your account’s exact window is under Profile, SMS Attributes, Posting Hours. The scheduling guide goes through what that does to timing.

For recurrence, it adds three rules:

  1. Validate the rule’s time when it’s created. A promotional rule at 22:00 will never go at 22:00. Reject it or move it in the UI, so the time your user sees is the time it really goes.
  2. Check the window again at catch-up time. A promotional run due at 20:00 that your scheduler picks up at 21:40 is now outside the window. With skip it’s stale anyway. With latest, hold it for the morning or skip it, but decide in code rather than letting it queue on the platform.
  3. Leave room before closing. A large weekly run at 20:55 that takes ten minutes to submit gets cut in half. Schedule promotional rules well inside the window.

Transactional messages (bill reminders, statements, OTPs) aren’t held by the window. Your own quiet hours still make sense for them. A courtesy “no reminders before 08:00 local time” rule, checked against the recipient’s zone, costs nothing.


Editing, Pausing and Ending a Rule

Edits create a new version. Copy the rule, change what was edited, bump version, and mark the old version superseded_at = now. A partial unique index on rule_id WHERE superseded_at IS NULL stops two live versions from ever existing at once. Occurrences keep the version that created them, so your report can say “March ran on v3, April on v4”.

If the edit changes the timing, set the new version’s anchor to the first date on or after today that fits the new pattern. Because occurrence keys are dates, any date already sent under the old version is safe. Text edits take effect on the next run that hasn’t been claimed. Make that visible in the UI: “Changes apply from the next run on 31 March.”

Pausing sets a state; resuming sets not_before. While a rule is paused, the scheduler doesn’t look at it. On resume, set not_before to the resume time. The planner ignores anything due before not_before, so the six weekly runs that fell inside a six-week pause don’t all fire at once on resume. This matches what the portal does (“Campaign resumes from the next scheduled trigger date”) and it’s what users expect.

Be careful with catch_up = 'all' here. “Send every missed run” is about runs missed because your system failed. It isn’t about runs a person chose to pause. not_before keeps those two apart.

Ending a rule happens three ways: until passes, count is used up, or someone stops it. In all three, set state = 'ended' and keep the row. Your reports, your audit trail and any “why did this person get a message on the 31st” question all need it. The portal keeps execution reports after a campaign is deleted, and so should you.

Deleting should be rare and should never remove the occurrence and send rows. Those are the record of what you sent. If a person asks you to erase their data, that’s a separate process, covered in the retention and erasure guide.


Checks Before Every Run

A rule is created once and runs for months. Everything it depends on can change in between, and nobody will think to tell the scheduler. So every run starts by checking.

CheckWhy it goes staleWhat to do if it fails
BalanceCredits run down between runsBlock the run with a reason, alert, and let the catch-up policy decide once it’s topped up
DLT templateEdited, re-registered with typed tags, or rejectedBlock the run; a template mismatch would fail every message anyway
Sender ID (header)Deleted, deactivated, or unlinked from the templateBlock the run
AudiencePeople join, leave, pay their billResolve the audience at run time, never at rule creation
Consent and suppressionPeople opt out between runsCheck each recipient; mark them suppressed, not failed
ContentAmount, date or balance changedRender the text at run time from current data
Posting windowLate pickup moved a promotional run past closingSkip or hold, per policy

A few notes on those.

Block, don’t fail. If the sender ID is inactive, sending 5,000 messages to get 5,000 rejections is pointless. Mark the occurrence blocked with the reason and raise an alert. The portal’s troubleshooting page lists the same causes for failed recurring runs: insufficient credits, an invalid or inactive sender ID, empty groups, an invalid DLT template ID. Catching them before the send turns a failed run into a held one.

Balance means the whole run. Estimate the run’s cost (recipients times parts times rate, as in the cost forecasting section) and compare it with your balance minus everything else already committed. The SMS pricing terms say the per-SMS rate is deducted “while sending SMS”, so having enough when the rule was created means nothing on the day.

Templates moved to typed tags. DLT templates now use typed variables such as {#numeric#} and {#alphanumeric#}, and moving an old {#var#} template over can give it a new template ID on some DLT portals. A rule created a year ago may still point at the old one. Store a template_key on the rule that maps to your current template record, not the raw DLT ID, and validate the rendered values against the tags on every run. The template management guide has a validator.

Consent is per recipient, per run. Someone who opted out on Tuesday must not get Wednesday’s run. Join each recipient against your suppression list and preference centre at run time, not at rule creation. The suppression guide and the preference centre guide cover the tables. Write a suppressed send row for each person you skip, so the run’s numbers add up.

The audience is a query. Store audience_ref (a segment ID, a saved filter, a group key) on the rule and resolve it at run time. If the audience is “people with an unpaid invoice”, the run on the 5th should only reach people unpaid on the 5th. The contact groups guide covers modelling segments.


The 90-Day Header Trap

This one only bites slow schedules, and it bites quietly.

TRAI’s February 2025 amendment brought in automatic deactivation of idle headers. The platform’s DLT header help page says it plainly: a header that sends “no messages for 90 days” is deactivated, and messages sent with it afterwards fail as an invalid or blocked sender. You then have to request reactivation on your DLT portal.

Now look at the gaps between runs of a quarterly rule that starts on 1 December 2026:

FromToDays between
2026-12-012027-03-0190
2027-03-012027-06-0192
2027-06-012027-09-0192
2027-09-012027-12-0191

If that renewal notice is the only thing that header ever sends, it’s at or past 90 days idle before every run. A yearly birthday or anniversary rule on a dedicated header is idle for 365 or 366 days. The rule fires, the header is dead, and every message fails.

Three ways out, in order of preference:

  1. Send slow rules from a header that carries other traffic. Your main transactional header sends every day. As long as the template is registered against it, there’s no idle gap to worry about. Remember a DLT template can only be linked to one header, so register the template against the busy one.
  2. Check the gap when the rule is saved. Compute the longest gap between consecutive runs over the next couple of years. If it’s over your threshold and the header has no other traffic, warn the user before they save.
  3. Check the header’s last use before each run. Keep a last_sent_at per header from your own send log. If it’s older than your threshold, block the run and alert, so someone can reactivate the header before the run is retried.

Use a threshold well under 90, say 75 days. Whether “90 days” counts calendar days in IST, whether the day of the last send counts, and how long reactivation takes are all things you’d rather not test in production.


Forecasting What a Rule Will Cost

A rule is a standing order for spend, so show the cost before someone saves it.

The arithmetic is simple, with two traps. Per run, the cost is recipients times parts times rate. Over a period, it’s that times the number of runs in the period.

Trap one: parts. A plain GSM message is one part up to 160 characters, but once it’s longer each part holds 153, because the concatenation header takes room. Unicode is 70 for one part and 67 per part after that. So a 200-character message is 2 parts, and so is a 306-character one, but 307 characters is 3. Rendered text varies by recipient (a long name, a bigger amount), so estimate from your longest likely rendering, or render every message and count. The SMS length calculator and the credit counting guide cover the details.

Trap two: runs. Count them from the rule, don’t multiply by 52 or 12. Here’s a weekly reminder to 5,000 people, 2 parts each, at an illustrative INR 0.15 per part:

ItemValue
One run5,000 x 2 x 0.15 = INR 1,500.00
Fridays in 2027 (rule starts Friday 1 January)53
Year at 53 runsINR 79,500.00
Year if you assumed 52 runsINR 78,000.00

The difference is one run’s cost. Small, but it’s the kind of gap that makes a budget conversation awkward. Do this with a decimal type, not floats. The preview and cost estimation guide shows how to price a message before it’s sent, and the pricing breakdown explains what drives the rate.

Remember the audience changes. A forecast is an estimate from today’s audience size, so label it that way and update it after each run with real numbers from your send rows.


The Schema

Three tables, one per object. This is Postgres-flavoured SQL; it also runs as written in SQLite, which is handy for tests.

CREATE TABLE recurrence_rule (
  rule_id       TEXT    NOT NULL,
  version       INTEGER NOT NULL,
  start_date    TEXT    NOT NULL,            -- anchor, local date YYYY-MM-DD
  at_time       TEXT    NOT NULL,            -- local HH:MM
  tz            TEXT    NOT NULL,            -- IANA zone name
  interval_n    INTEGER NOT NULL CHECK (interval_n BETWEEN 1 AND 999),
  unit          TEXT    NOT NULL CHECK (unit IN ('day', 'week', 'month', 'year')),
  month_end     TEXT    NOT NULL DEFAULT 'clamp' CHECK (month_end IN ('clamp', 'skip')),
  until_date    TEXT,                        -- inclusive, local
  max_count     INTEGER,
  catch_up      TEXT    NOT NULL DEFAULT 'skip' CHECK (catch_up IN ('skip', 'latest', 'all')),
  max_late_s    INTEGER NOT NULL DEFAULT 7200,
  audience_ref  TEXT    NOT NULL,            -- a segment query, resolved per occurrence
  template_key  TEXT    NOT NULL,
  sender_key    TEXT    NOT NULL,
  purpose       TEXT    NOT NULL,            -- for the consent check
  state         TEXT    NOT NULL CHECK (state IN ('active', 'paused', 'ended')),
  not_before    TIMESTAMPTZ NOT NULL,        -- created or last resumed
  superseded_at TIMESTAMPTZ,                 -- set when a newer version takes over
  created_at    TIMESTAMPTZ NOT NULL,
  PRIMARY KEY (rule_id, version)
);
CREATE UNIQUE INDEX one_live_version ON recurrence_rule (rule_id) WHERE superseded_at IS NULL;

CREATE TABLE recurrence_occurrence (
  occ_key       TEXT PRIMARY KEY,            -- rule_id:local_date
  rule_id       TEXT    NOT NULL,
  rule_version  INTEGER NOT NULL,
  local_date    TEXT    NOT NULL,
  due_utc       TIMESTAMPTZ NOT NULL,
  state         TEXT    NOT NULL CHECK (state IN
                  ('pending', 'claimed', 'booked', 'sent', 'partial', 'failed', 'skipped', 'blocked')),
  reason        TEXT,                        -- why skipped, blocked or failed
  claimed_by    TEXT,
  claimed_until TIMESTAMPTZ,
  recipients    INTEGER,
  accepted      INTEGER,
  finished_at   TIMESTAMPTZ
);
CREATE INDEX occ_due ON recurrence_occurrence (state, due_utc);

CREATE TABLE recurrence_send (
  send_key        TEXT PRIMARY KEY,          -- hash of occ_key and recipient
  occ_key         TEXT NOT NULL REFERENCES recurrence_occurrence (occ_key),
  recipient       TEXT NOT NULL,
  state           TEXT NOT NULL CHECK (state IN ('queued', 'accepted', 'rejected', 'suppressed')),
  provider_txn_id TEXT,                      -- always text, never a number
  error           TEXT,
  created_at      TIMESTAMPTZ NOT NULL
);

one_live_version is the partial unique index that makes “edit means new version” safe. Two admins saving at the same moment can’t both create a live version.

recurrence_occurrence.occ_key is the primary key, so computing the same occurrence twice is a conflict, not a duplicate run. Insert with ON CONFLICT (occ_key) DO NOTHING.

state has two failure-ish values that mean different things, plus booked for runs handed to the platform ahead of time (see the sending section). failed means you tried and the provider said no to everyone. blocked means preflight stopped you before you tried. Your alerting should treat them differently: blocked usually needs a person (top up, reactivate a header), failed usually needs an engineer.

recurrence_send.provider_txn_id is TEXT. Always. If you already have an outbound message table, you can make recurrence_send a thin link table that points at it instead of repeating columns.

Claiming due occurrences in Postgres looks like this:

UPDATE recurrence_occurrence
SET    state = 'claimed', claimed_by = $1, claimed_until = now() + interval '5 minutes'
WHERE  occ_key IN (
  SELECT occ_key FROM recurrence_occurrence
  WHERE  (state = 'pending' AND due_utc <= now())
     OR  (state = 'claimed' AND claimed_until < now())
  ORDER  BY due_utc
  LIMIT  50
  FOR UPDATE SKIP LOCKED
)
RETURNING occ_key;

The second OR branch is lease recovery: an occurrence whose worker died gets picked up again once its lease runs out. And one monitoring query is worth having from day one, because it catches the scheduler being down:

SELECT rule_id, occ_key, due_utc
FROM   recurrence_occurrence
WHERE  state IN ('pending', 'claimed')
  AND  due_utc < now() - interval '15 minutes';

Anything it returns is a run that should have finished and hasn’t.


The Engine in Python

Here’s the recurrence core. It’s standard library only (zoneinfo needs Python 3.9 or later), it has no database code, and it does four jobs: compute occurrences from the anchor, convert them to UTC, split what’s due into send and skip by policy, and measure the longest gap for the header check.

"""Anchored recurrence for scheduled messages. Standard library only."""
from __future__ import annotations

import calendar
import hashlib
from dataclasses import dataclass
from datetime import date, datetime, time, timedelta, timezone
from typing import Iterator, Optional
from zoneinfo import ZoneInfo

UNITS = ("day", "week", "month", "year")
CATCH_UP = ("skip", "latest", "all")


@dataclass(frozen=True)
class Rule:
    rule_id: str
    version: int
    start: date                      # the anchor: first local date
    at: time                         # local wall-clock time
    tz: str                          # IANA zone, e.g. "Asia/Kolkata"
    interval: int                    # 1 to 999, like the portal
    unit: str                        # day | week | month | year
    month_end: str = "clamp"         # clamp | skip
    until: Optional[date] = None     # last local date, inclusive
    count: Optional[int] = None      # stop after this many occurrences
    catch_up: str = "skip"           # skip | latest | all
    max_late: timedelta = timedelta(hours=2)

    def __post_init__(self):
        if self.unit not in UNITS:
            raise ValueError(f"unit must be one of {UNITS}")
        if not 1 <= self.interval <= 999:
            raise ValueError("interval must be 1 to 999")
        if self.month_end not in ("clamp", "skip"):
            raise ValueError("month_end must be clamp or skip")
        if self.catch_up not in CATCH_UP:
            raise ValueError(f"catch_up must be one of {CATCH_UP}")
        if self.until is not None and self.until < self.start:
            raise ValueError("until is before start")
        ZoneInfo(self.tz)  # raises if the zone name is wrong


@dataclass(frozen=True)
class Occurrence:
    key: str          # rule_id + local date: stable across edits
    n: int            # step number from the anchor
    local_date: date
    due_utc: datetime


def _shift(d: date, unit: str, k: int, month_end: str) -> Optional[date]:
    """Move k units from the ANCHOR. Returns None for a skipped month end."""
    if unit == "day":
        return d + timedelta(days=k)
    if unit == "week":
        return d + timedelta(weeks=k)
    months = k if unit == "month" else 12 * k
    y = d.year + (d.month - 1 + months) // 12
    m = (d.month - 1 + months) % 12 + 1
    last = calendar.monthrange(y, m)[1]
    if d.day <= last:
        return date(y, m, d.day)
    return date(y, m, last) if month_end == "clamp" else None


def to_utc(rule: Rule, d: date) -> datetime:
    """Local date plus wall-clock time, in UTC. A time that falls in a DST
    gap comes out one hour later on the wall clock (fold=0 behaviour)."""
    local = datetime.combine(d, rule.at, tzinfo=ZoneInfo(rule.tz))
    return local.astimezone(timezone.utc)


def occurrence_key(rule: Rule, d: date) -> str:
    return f"{rule.rule_id}:{d.isoformat()}"


def send_key(occ_key: str, recipient: str) -> str:
    """Idempotency key for one recipient of one occurrence."""
    return hashlib.sha256(f"{occ_key}|{recipient}".encode()).hexdigest()[:32]


def occurrences(rule: Rule) -> Iterator[Occurrence]:
    """Every occurrence in order, computed from the anchor each time."""
    n, emitted = 0, 0
    while True:
        if rule.count is not None and emitted >= rule.count:
            return
        d = _shift(rule.start, rule.unit, n * rule.interval, rule.month_end)
        if d is not None:
            if rule.until is not None and d > rule.until:
                return
            emitted += 1
            yield Occurrence(occurrence_key(rule, d), n, d, to_utc(rule, d))
        n += 1


def next_after(rule: Rule, t: datetime) -> Optional[Occurrence]:
    for occ in occurrences(rule):
        if occ.due_utc > t:
            return occ
    return None


def plan(rule: Rule, now: datetime, not_before: datetime,
         last_done: Optional[date] = None):
    """Split the occurrences that are due now into (send, skip).

    not_before: when the rule was created or last resumed. Nothing due
    earlier is ever sent, so a pause never turns into a burst.
    last_done: local date of the newest occurrence already sent or skipped.
    """
    due = []
    for occ in occurrences(rule):
        if occ.due_utc > now:
            break
        if occ.due_utc < not_before:
            continue
        if last_done is not None and occ.local_date <= last_done:
            continue
        due.append(occ)
    if not due:
        return [], []
    if rule.catch_up == "all":
        return due, []
    if rule.catch_up == "latest":
        return due[-1:], due[:-1]
    fresh = [o for o in due if now - o.due_utc <= rule.max_late]
    return fresh[-1:], [o for o in due if o not in fresh[-1:]]


def max_gap_days(rule: Rule, horizon: int = 24) -> int:
    """Largest gap in days between consecutive occurrences in the horizon."""
    dates = []
    for occ in occurrences(rule):
        dates.append(occ.local_date)
        if len(dates) > horizon:
            break
    return max((b - a).days for a, b in zip(dates, dates[1:])) if len(dates) > 1 else 0

_shift always starts from the anchor. occurrences calls it with n * interval for each n, so no date ever depends on the date before it.

to_utc builds the local datetime with the rule’s zone and converts it. For a wall-clock time inside a DST gap, Python’s zoneinfo (with the default fold=0) gives you the time an hour later on the wall clock, which is the “send it, a bit late” behaviour described earlier.

plan never looks at the clock itself. You pass now, which makes it trivial to test, and you pass not_before and last_done from your database. It returns two lists so your caller can write skipped rows for the second one.

occurrence_key uses the local date, so it survives edits to the time of day, as discussed in the occurrence keys section.

The tick that drives it is short. For each active rule: load last_done (the newest local_date that’s sent, partial, failed, skipped or blocked), call plan, insert the occurrences to send as pending and the rest as skipped (both with ON CONFLICT DO NOTHING), then let workers claim pending rows with the query above. Run the tick every minute. Because everything it writes is keyed, running it twice, or on two machines, does no harm.

And here’s the worker that runs one claimed occurrence. It does the preflight, writes one keyed send row per recipient, sends the ones still queued, and works out the final state.

"""Run one occurrence: preflight, per-recipient keys, send, record."""
import requests

from recur import send_key

BASE = "https://unify.smsgateway.center"


def _inner(body):
    if isinstance(body, dict) and isinstance(body.get("response"), dict):
        return body["response"]
    return body if isinstance(body, dict) else {}


def send_one(creds, sender, mobile, text, timeout=20):
    """One SMSApi/send call. Returns (accepted, transaction id or None, reason)."""
    data = {"userid": creds["userid"], "sendMethod": "quick", "mobile": mobile,
            "msg": text, "senderid": sender, "msgType": "text", "output": "json"}
    try:
        r = requests.post(f"{BASE}/SMSApi/send", data=data,
                          headers={"apikey": creds["apikey"]}, timeout=timeout)
        body = r.json()
    except (requests.RequestException, ValueError) as exc:
        return False, None, f"transport: {exc.__class__.__name__}"
    inner = _inner(body)
    if inner.get("status") != "success":
        return False, None, "provider said no"
    txn = inner.get("transactionId")
    return True, (str(txn) if txn is not None else None), "ok"


def run_occurrence(db, occ_key, recipients, render, sender, creds, preflight, now):
    """recipients: list of mobile numbers already resolved for THIS occurrence.
    preflight(): returns None if OK, or a reason string to block the run.
    Safe to call again after a crash: a recipient with an accepted row is
    never sent twice."""
    reason = preflight()
    if reason:
        db.execute("UPDATE recurrence_occurrence SET state='blocked', reason=?, finished_at=? "
                   "WHERE occ_key=?", (reason, now, occ_key))
        db.commit()
        return "blocked"
    for mobile in recipients:
        db.execute("INSERT INTO recurrence_send (send_key, occ_key, recipient, state, created_at) "
                   "VALUES (?, ?, ?, 'queued', ?) ON CONFLICT (send_key) DO NOTHING",
                   (send_key(occ_key, mobile), occ_key, mobile, now))
    db.commit()
    todo = db.execute("SELECT send_key, recipient FROM recurrence_send "
                      "WHERE occ_key=? AND state='queued'", (occ_key,)).fetchall()
    for key, mobile in todo:
        ok, txn, why = send_one(creds, sender, mobile, render(mobile))
        if ok:
            db.execute("UPDATE recurrence_send SET state='accepted', provider_txn_id=? "
                       "WHERE send_key=?", (txn, key))
        elif why.startswith("transport"):
            db.execute("UPDATE recurrence_send SET error=? WHERE send_key=?", (why, key))
        else:
            db.execute("UPDATE recurrence_send SET state='rejected', error=? WHERE send_key=?",
                       (why, key))
        db.commit()
    total, accepted, queued = db.execute(
        "SELECT COUNT(*), SUM(state='accepted'), SUM(state='queued') "
        "FROM recurrence_send WHERE occ_key=?", (occ_key,)).fetchone()
    if queued:
        return "retry"
    state = "sent" if accepted == total else ("failed" if not accepted else "partial")
    db.execute("UPDATE recurrence_occurrence SET state=?, recipients=?, accepted=?, finished_at=? "
               "WHERE occ_key=?", (state, total, accepted, now, occ_key))
    db.commit()
    return state

A run that hits a network error part way through returns retry and leaves the rest of the rows queued. When the lease runs out, the next worker picks it up and sends only those. A recipient whose row is accepted is never sent again. That’s the crash-safety property, and it’s tested below.

Two things to adapt. The worker sends one quick call per recipient, which keeps the per-recipient bookkeeping exact and lets each message carry its own rendered text. For a large run where the text is identical for everyone, a group send is cheaper on round trips, but you then get one transaction for the whole group and need the delivery report ingestion side to break it down per number. And the worker reads only status, never statusCode or reason, so it keeps working if those fields change type or wording.


Handing a Run to SMSApi/send

Each send in a run is an ordinary SMS API call. Use the apikey header with userid; the header works on every endpoint.

curl -s -X POST 'https://unify.smsgateway.center/SMSApi/send' \
  -H "apikey: ${SGC_APIKEY}" \
  --data-urlencode "userid=${SGC_USERID}" \
  --data-urlencode 'sendMethod=quick' \
  --data-urlencode 'mobile=919999999999' \
  --data-urlencode 'senderid=ABCDEF' \
  --data-urlencode 'msgType=text' \
  --data-urlencode 'msg=Dear Asha, your bill of Rs 2340 is due on 05-04-2027. Pay at your branch or online. - ABCDEF' \
  --data-urlencode 'output=json'

The text has to match the DLT template registered for that header, with each value fitting its typed tag. A success looks like this:

{
  "status": "success",
  "mobile": "919999999999",
  "invalidMobile": "",
  "transactionId": "6305583318236810379",
  "statusCode": "200",
  "reason": "success"
}

Save transactionId on the send row as text before you do anything else. It’s what joins this run to its delivery reports.

Sending at the due time or booking ahead. The worker above sends when the run is due. That’s the simplest setup and it lets every check happen at the last moment. The cost is that a scheduler outage at 09:00 delays the run.

If that matters more than last-second checks, book SMS runs ahead: when a run is, say, 30 minutes away, do the preflight, render the messages, and send them with scheduleTime (YYYY-MM-DD HH:MM:SS) set to the due time. Store the transactionId, read the booking back with SMSApi/schedule/read, and mark the occurrence booked. If someone pauses the rule or a recipient opts out before the due time, cancel with SMSApi/schedule/delete. The scheduling guide has the full handoff, including the cancel cutoff and the time zone probe you need before trusting scheduleTime.

Booking ahead only works for SMS. WhatsApp’s scheduletime can’t be cancelled through the API, and RCS and Telegram don’t take a schedule time, so runs on those channels go out from your own worker at the due time.

Other channels. Nothing in the rule or occurrence layers is SMS-specific. To run a rule on WhatsApp, swap send_one for a WAApi/send call with an approved template. One extra check applies there: a free-form WhatsApp message needs an open customer service window, so a recurring WhatsApp rule should always send a template. The 24-hour window guide explains why.


Testing a Year of Schedules in a Second

Recurrence bugs live on dates you won’t reach for months. So don’t wait for them. Every function in the engine takes dates and now as arguments, which means you can test a whole year of edge cases instantly.

These are the cases worth a test each, and the engine above passes all of them:

CaseExpected
Monthly from 31 January 2027Jan 31, Feb 28, Mar 31, Apr 30, May 31, Jun 30
Same, chained from the last runDrifts to Mar 28, Apr 28 (the bug you’re avoiding)
Monthly from 31 January with skipJan 31, Mar 31, May 31, Jul 31
Yearly from 29 February 2028, clamp2028-02-29, then Feb 28 in 2029 to 2031, 2032-02-29
Daily 09:00 IST03:30 UTC
Weekly 09:00 New York across 1 November 202613:00 UTC on 29 Oct, 14:00 UTC on 5 Nov
02:30 New York on 14 March 2027 (DST gap)07:30 UTC (03:30 local)
Weekly until 15 January 2027 from 1 JanuaryJan 1, 8, 15 (inclusive)
Weekly Fridays through 202753 runs
skip, 30 minutes late, max_late 2 hoursSends the newest, skips older
skip, 5.5 hours lateSends nothing
latest, 5.5 hours lateSends the newest only
Resumed after a pauseNothing before the resume time is sent
Time moved from 09:00 to 18:00 on the same daySame occurrence key, no second run
Quarterly from 1 December 2026Longest gap 92 days
Worker crashes after 2 of 4 sends, then rerunsEach number sent exactly once

Here’s a slice of the test file, so you can see the shape:

def test_month_end_anchored(self):
    got = [str(o.local_date) for o in first(r(), 6)]
    self.assertEqual(got, ["2027-01-31", "2027-02-28", "2027-03-31",
                           "2027-04-30", "2027-05-31", "2027-06-30"])

def test_new_york_dst(self):
    rule = r(start=date(2026, 10, 29), unit="week", tz="America/New_York")
    a, b = first(rule, 2)
    self.assertEqual(a.due_utc, datetime(2026, 10, 29, 13, 0, tzinfo=UTC))
    self.assertEqual(b.due_utc, datetime(2026, 11, 5, 14, 0, tzinfo=UTC))

def test_catch_up_policies(self):
    base = dict(start=date(2027, 1, 1), unit="day")
    nb = datetime(2026, 12, 31, tzinfo=UTC)
    later = datetime(2027, 1, 4, 9, 0, tzinfo=UTC)   # 14:30 IST, past max_late
    send, skip = plan(r(**base, catch_up="skip"), later, nb)
    self.assertEqual(send, [])
    send, skip = plan(r(**base, catch_up="latest"), later, nb)
    self.assertEqual([str(o.local_date) for o in send], ["2027-01-04"])

r() is a small helper that builds a monthly rule anchored on 31 January 2027 at 09:00 IST, with keyword overrides. For the worker, inject a fake requests module that fails after a set number of calls, run the occurrence, rerun it, and assert each number was sent exactly once. For the platform side, a contract test against the sandbox catches a changed response shape before your scheduler does.

One more test that’s easy to forget: run your tick twice in a row with the same now and assert the second one creates nothing. That’s the property every other safety net depends on.


Decision Matrix

SituationUseWhy
A person sets up a fixed monthly reminder for an uploaded groupPortal Recurring SMSNo code to own; reports included
Your users create their own schedules in your appYour own engineSchedules live in your data and your UI
The audience is “everyone unpaid today”Your own engineThe audience is resolved per run
The text includes today’s amount or dateYour own engineRendered per run, per person
Monthly on the 29th, 30th or 31stAnchored dates, clampNo drift to the 28th
A record must exist for every periodcatch_up = allMissed periods are sent in order
One message covers the current statecatch_up = latestThe customer gets the current one, not a pile
The message is about nowcatch_up = skip, short max_lateStale offers don’t go out
Quarterly or yearly from a dedicated headerMove to a busy header, or watch last_sent_atThe 90-day idle rule deactivates headers
Runs must go out even if your scheduler is downBook SMS ahead with scheduleTimeThe platform holds the booking
Runs need last-second consent and content checksSend at the due timeNothing is frozen early
WhatsApp on a scheduleTemplate messages from your own workerBookings can’t be cancelled; free-form needs an open window

Before You Go Live

  • Every date is computed from the rule’s anchor, and there’s a test for 31 January monthly
  • Month-end behaviour (clamp or skip) is stored on the rule and shown to the user
  • until is inclusive, and the UI says so
  • Rules store an IANA zone, not an offset, and due times are computed per run
  • Occurrence key is rule_id:local_date, primary key, inserted with ON CONFLICT DO NOTHING
  • Send key is a hash of occurrence key and recipient, primary key
  • Workers claim with a lease and FOR UPDATE SKIP LOCKED; expired leases are reclaimed
  • Each rule has a catch-up policy and a max_late
  • Resume sets not_before; paused dates are never replayed
  • Edits create a new version; a partial unique index allows one live version per rule
  • Preflight checks balance, template, sender ID, posting window and per-recipient consent
  • The audience and the text are resolved at run time
  • Promotional rules are validated against the posting window when saved
  • The longest gap between runs is checked against a 75-day threshold for the rule’s header
  • Cost forecasts count actual runs and use a decimal type
  • transactionId is stored as text on every send row
  • Skipped and blocked runs are rows with a reason, and both raise alerts
  • A monitoring query flags occurrences more than 15 minutes overdue
  • Running the tick twice with the same now creates nothing the second time

Unspecified Behaviour and How to Code Around It

Some behaviours that matter to a recurring sender aren’t pinned down by anything you can read, either on the platform or in the regulations. Each item below gives you the choice that stays safe whichever way the answer turns out, so none of them needs you to wait for one.

One. Count a header’s idle time conservatively. Whether the 90 days run in calendar days, whether the day of the last send counts, and how long reactivation takes aren’t spelled out. Warn at 75 days and block at 85. A rule that’s blocked for a day is an alert; a dead header on renewal day is an outage.

Two. Treat “monthly on the 31st” in the portal as unknown, and keep such rules in your engine. How the portal handles a start date of the 29th to 31st in a shorter month isn’t stated, and its edit behaviour recalculates from the last execution. If month-end dates matter, run those rules in your own engine where the anchor and the clamp or skip choice are explicit.

Three. Assume a portal run can land up to 10 minutes late, and keep time-critical messages out of it. The help pages say due campaigns are checked “every few minutes” and messages “may be sent within 5-10 minutes”. For a reminder, who cares. For anything with a deadline measured in minutes, send from your own worker.

Four. Store the platform’s timestamps alongside your own, and trust yours for scheduling. If you book runs ahead with scheduleTime, you’re sending a wall-clock string with no zone. Run the one-booking probe from the scheduling guide, store the offset you measured, and fail closed if a later read-back disagrees. A wrong zone then becomes a held booking, not a message sent five and a half hours off.

Five. Never infer a missed portal run from silence. The portal’s own failed-run behaviour is to carry on at the next execution. If you mirror portal campaigns in your own reporting, reconcile against execution reports or delivery reports by transaction ID. A run with no report row is “unknown”, never “didn’t send”.

Six. Pause your own rule before you touch the platform side. Whether an edit or pause reaches a booking that’s already handed off isn’t something you can see. Set the rule to paused in your database first, then cancel any handed-off SMS bookings with SMSApi/schedule/delete, then read the schedule list back. If the read-back still shows the booking and you’re inside your cancel cutoff, let it go and log it, rather than guessing.

Seven. Budget for a run as if every message will be charged. The per-SMS rate is deducted while sending, and you can’t know in advance which numbers will fail. Reserve the full run’s cost at preflight and release what’s left after the run. Over-reserving delays a run; under-reserving fails it halfway.

Eight. Resolve “until” in the rule’s own zone. An end date of 31 March means 31 March where the rule lives. Compare local dates, never UTC dates: a New York rule at 21:00 on 31 March 2027 is 01:00 UTC on 1 April, and a UTC comparison would drop it.

Nine. Key on the slot, not the version, even when you’re sure edits are rare. Whether your users edit schedules at 08:59 isn’t something you control. A date-based key makes the answer irrelevant: an edited rule can’t revisit a date that’s already been sent.

Ten. Check typed-tag values on every run, not once at rule creation. Whether a value will fit its DLT tag depends on the data on the day. A name that’s grown a link, an amount with a comma, a callback number with a +91: validate each rendered message against its tags and write a rejected send row for the ones that fail, instead of letting the operator reject them.

Eleven. Treat a frequency change as a new rule with a new anchor. Whether “monthly to weekly” should keep the old start day or start from today is a product question, and different users expect different things. Make the new anchor explicit in the edit screen (“Next run: Friday 9 April”) so whatever the user picks, they’ve seen it.


FAQs

Can I create portal Recurring SMS campaigns through the API?

No. Recurring SMS is set up, paused and edited in the dashboard. If you need schedules created from your own code, build a small engine like the one on this page and send each run through SMSApi/send.

Why does my monthly reminder keep landing on the 28th?

Because your scheduler adds a month to the last run instead of to the start date. After February, “28th plus a month” is the 28th forever. Compute run n as the start date plus n months, and clamp to the month’s last day only for that one run.

What should happen to runs that were missed while my server was down?

It depends on the message. Skip stale ones for offers and “now” reminders, send only the newest for state-based reminders like bills, and send all of them for records like statements. Store the policy and a maximum lateness on each rule.

How do I stop a recurring SMS from being sent twice?

Give every run a key made of the rule ID and the local date, and every recipient a key derived from that run key and the phone number. Make both primary keys. Retries, crashes and duplicate workers then hit conflicts instead of sending again.

If someone edits the send time on the same day, will it go out twice?

Not if the run key is the date. The 09:00 run and the edited 18:00 run share the same key, so the second one finds the first already sent and does nothing.

What happens to runs during a pause?

They’re skipped. When the rule resumes, set not_before to the resume time and only send runs due after it. That’s also how the portal behaves: a resumed campaign carries on from its next trigger date.

Why would a quarterly SMS suddenly fail with a sender error?

Probably an idle header. A DLT header that sends nothing for 90 days is deactivated, and quarterly gaps run from 90 to 92 days. Send slow rules from a header that carries daily traffic, or check the header’s last use before each run.

How many times does a weekly rule run in a year?

Count it from the rule. It’s usually 52, but a year that starts on the rule’s weekday can have 53 (2027 has 53 Fridays). Budget from the counted number.

Do I need to worry about daylight saving?

Not for Indian recipients, because India doesn’t use it. For recipients abroad, yes: store an IANA zone with the rule and compute each run’s UTC time from the local date and time. 09:00 in New York is 13:00 UTC before 1 November 2026 and 14:00 UTC after.

Should I book runs ahead with scheduleTime or send them at the due time?

Send at the due time if you want last-second consent and content checks. Book SMS ahead (about 30 minutes) if runs must go out even when your scheduler is down. Either way, your database stays the master copy.

Can I run the same schedule on WhatsApp?

Yes, the rule and run layers don’t care about the channel. Swap the send step for WAApi/send with an approved template, and don’t book WhatsApp runs ahead, because those bookings can’t be cancelled through the API.

How do I estimate what a recurring rule will cost?

Recipients times message parts times rate, times the number of runs you counted. Parts are 160 characters for a single GSM message but 153 per part once it’s longer (70 and 67 for Unicode). Use a decimal type and update the forecast after each run.


Keep Every Reminder On Its Date and Never Twice

Your recurring messages are only as good as the scheduler behind them and the gateway in front of it. Create a free SMSGatewayCenter account, try sends and schedule bookings in the sandbox, and point your first rule at the SMS API. If you’d rather set up a fixed reminder without code, the Recurring SMS feature runs it from the dashboard. Questions about your setup? Talk to us.


More from our blog

Hardening Webhook Receivers for SMS and WhatsApp: Secrets, Duplicates and the Push That Never Came

The WhatsApp 24-Hour Window as a State Machine: Session Replies, Templates and a Send Router That Never Guesses

WhatsApp Template Buttons End to End: Quick Reply Payloads, Dynamic URL Buttons and Matching the Tap


Save this interesting page on your favorite Social Media

Blog Author logo

SMS Gateway Center Desk

SMS Gateway Center is one of the largest and leading SMS Provider in India. It is run by a large professional team to cater small companies to large corporate companies. SMS Gateway Center is associated with the best operators in India covering the entire states in India. SMS Gateway Center has been serving through its SMS Resellers in more than 20 states in India. To become our SMS Reseller, kindly contact us

Looking for the best business communication solutions, get in touch!