Run things periodically

The world runs on timetables, and sometimes so does your code. We’re pleased to announce that you can now run Background Tasks automatically according to a schedule.

Like cron for your Anvil apps.

Like cron for your Anvil apps.

This feature currently requires an Individal plan or higher.

With Scheduled Tasks, Anvil is a task scheduler, as well as a web app builder. You might even build apps with no UI at all!

Now you can use Anvil to do things like:

  • Sending SMS reminders to users (see below)
  • Automating some hardware
  • Sending yourself a daily report on your app’s user activity
  • Scheduling test runs nightly or weekly
  • Sending out a monthly email newsletter
  • Creating a calendar app that sends out alerts
  • Grabbing data regularly from an API to display in a dashboard

Here’s one example:

Example: SMS appointment reminders

Whether you’re running a medical clinic, a legal firm, or a chain of dressmakers, you always want to improve attendance rates for appointments. Sending your clients an SMS reminder an hour before their appointment is a great way to make sure they know when and where to turn up.

This is easy to achieve with a Scheduled Task. Every minute or so, run a task that checks the appointments table and sends a reminder to anybody who has an appointment in the next hour:

Imagine you have a Data Table for your customers’ appointments, with columns called customer, when and reminder_sent:

Here’s a simple function that queries the appointments table, and sends reminders for all appointments in the next hour:

@anvil.server.background_task
def send_reminders():
  """Send reminders for all appointments in the next hour,
     if a reminder has not already been sent."""
  appointments_soon = app_tables.appointments.search(
    when=q.between(
      datetime.now(),
      datetime.now() + timedelta(hours=1),
    ),
    reminder_sent=False,
  )
  for appointment in appointments_soon:
    send_sms(appointment)
    appointment['reminder_sent'] = True

Every minute, this will get run by the Scheduled Tasks system, and your users will get their reminders:

To learn more about using SMS with Anvil, read our guide to creating an SMS poll using Nexmo, or try out the Twilio Python API (which is available in Server Modules).

You can also use this pattern to send out any scheduled communications, such as email (using the Email Service), or Twitter (using the Twitter REST API or one of the Twitter Python APIs).

How to try Anvil

If you’re new here, welcome! Anvil is a drag-and-drop web app builder that runs Python in the browser as well as in a hosted server environment… and we found that using one language for everything makes the whole stack so much simpler! It’s free to use, with a few premium features such as Scheduled Tasks.

Just click here to get started: