Schedule Cron Jobs to Call API with Supabase

I recently needed Cron jobs for a project and was, as usual, happily surprised by how easy Supabase made it.

To run Cron jobs on Supabase, you must first enable the pg_cron extension.

In your SQL editor in Supabase (which can be found at https://supabase.com/dashboard/project/YOUR_PROJECT_ID/sql/new) you can run the following:

-- Example: enable the "pg_cron" extension
create extension pg_cron with schema extensions;

grant usage on schema cron to postgres;
grant all privileges on all tables in schema cron to postgres;

-- Example: disable the "pg_cron" extension
drop extension if exists pg_cron;

This will enable pg_cron.

Next, we can set up a Cron that will call an API endpoint; in this example, I'll use a Supabase Edge function (but it could be any endpoint you want).

Set up your Cron

There are a few values here to be careful with, as you'll need to update them for your use case.

The Cron name is 'invoke-function-every-minute'; you can alter this to whatever is suitable for you.

  • To understand how Cron timing works and generate the syntax, I recommend using something like crontab.guru, which will make the * * * * * syntax understandable.

  • I also pass an auth token with each request to confirm on the server side that it has permission to do whatever it's trying to do (you'll see that in "Authorization": "Bearer YOUR_ANON_KEY").

  • The URL you try to hit can be altered under the URL string. Currently, we have 'https://YOUR_PROJECT_ID.supabase.co/functions/v1/some-function'. This needs to be updated to be an actual endpoint you can hit.

select
  cron.schedule(
    'invoke-function-every-minute',
    '* * * * *', -- every minute
    $$
    select
      net.http_post(
          url:='https://YOUR_PROJECT_ID.supabase.co/functions/v1/some-function',
          headers:='{"Content-Type": "application/json", "Authorization": "Bearer YOUR_ANON_KEY"}'::jsonb,
          body:=concat('{"time": "', now(), '"}')::jsonb
      ) as request_id;
    $$
  );

Unschedule

To unschedule, we need to unscheduled by our Cron name, in this case 'invoke-function-every-minute':

select cron.unschedule('invoke-function-every-minute');

Notes

The Supabase docs are some of the best, so if you get stuck, check out this page.

SupabaseCron
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.