# Scheduling Edge Functions

Schedule Edge Functions with pg_cron.



The hosted Supabase Platform supports the [`pg_cron` extension](https://supabase.com/docs/guides/database/extensions/pg_cron), a recurring job scheduler in Postgres.

In combination with the [`pg_net` extension](https://supabase.com/docs/guides/database/extensions/pg_net), this allows us to invoke Edge Functions periodically on a set schedule.

Caution: To access the auth token securely for your Edge Function call, we recommend storing them in [Supabase Vault](https://supabase.com/docs/guides/database/vault).

## Examples

### Invoke an Edge Function every minute

Call the function with your secret key. Don't use your publishable key, because it's public and anyone who has it can call a function that accepts it. Store your project URL and secret key in Supabase Vault:

```sql
select vault.create_secret('https://project-ref.supabase.co', 'project_url');
select vault.create_secret('YOUR_SUPABASE_SECRET_KEY', 'secret_key');
```

Make a POST request to a Supabase Edge Function every minute:

```sql
select
  cron.schedule(
    'invoke-function-every-minute',
    '* * * * *', -- every minute
    $$
    select
      net.http_post(
          url:= (select decrypted_secret from vault.decrypted_secrets where name = 'project_url') || '/functions/v1/function-name',
          headers:=jsonb_build_object(
            'Content-type', 'application/json',
            'apikey', (select decrypted_secret from vault.decrypted_secrets where name = 'secret_key')
          ),
          body:=concat('{"time": "', now(), '"}')::jsonb
      ) as request_id;
    $$
  );
```

The function receives the secret key on the `apikey` header. To accept it, disable `verify_jwt` and use `auth: 'secret'`. For more information, see [Service-to-service calls](https://supabase.com/docs/guides/functions/auth#service-to-service-calls).

Caution: Any role that can log in to your database can read the secret key while the request waits. `pg_net` [writes the decrypted key to `net.http_request_queue`](https://supabase.com/kb/troubleshooting/database-roles-can-read-request-headers-queued-by-pg_net-ad6357) until it sends the request.

## Resources

- [`pg_net` extension](https://supabase.com/docs/guides/database/extensions/pg_net)
- [`pg_cron` extension](https://supabase.com/docs/guides/database/extensions/pg_cron)
