# pg_cron

import { Aside, CardGrid, LinkCard } from '@astrojs/starlight/components';

Use pg_cron to run pgflow workflows on a recurring schedule for time-based automation tasks.

<Aside type="note">
For complete pg_cron documentation including cron expression syntax, job management, and configuration options, see:
- [Supabase pg_cron Guide](https://supabase.com/docs/guides/database/extensions/pg_cron)
- [pg_cron GitHub Repository](https://github.com/citusdata/pg_cron)
</Aside>

## Basic Usage

Schedule a workflow to run every 30 minutes:

```sql
SELECT cron.schedule(
  'collect-urls',
  '*/30 * * * *',
  $$
    SELECT pgflow.start_flow(
      flow_slug => 'collect_urls',
      input => jsonb_build_object('sources', ARRAY['news', 'blogs'])
    )
  $$
);
```

## Processing Recent Records

Query your database and start workflows for matching records. This example processes all orders created in the last 24 hours:

```sql
SELECT cron.schedule(
  'process-new-orders',
  '0 2 * * *',  -- Daily at 2 AM
  $$
    SELECT pgflow.start_flow(
      flow_slug => 'process_order',
      input => jsonb_build_object(
        'order_id', order_id,
        'customer_email', customer_email,
        'total_amount', total_amount
      )
    )
    FROM public.orders
    WHERE created_at >= NOW() - INTERVAL '24 hours'
      AND status = 'pending'
  $$
);
```

This pattern starts one workflow for each matching row, passing the row's data as input to the workflow.

## Learn More

<CardGrid>
  <LinkCard
    title="Database Triggers"
    href="/build/starting-flows/database-triggers/"
    description="Start workflows automatically when data changes"
  />
</CardGrid>