Skip to content

Commit c7e1922

Browse files
ldecarvalho-docLaure-di
authored andcommitted
feat(rdb): pgcron - MTA-5588 (scaleway#4442)
1 parent 89adff5 commit c7e1922

File tree

2 files changed

+216
-0
lines changed

2 files changed

+216
-0
lines changed

menu/navigation.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2426,6 +2426,10 @@
24262426
"label": "Setting up and using the pgaudit extension",
24272427
"slug": "pg-audit"
24282428
},
2429+
{
2430+
"label": "Setting up and using the pg_cron extension",
2431+
"slug": "using-pgcron"
2432+
},
24292433
{
24302434
"label": "Verifying Servers' Certificate Authority on PostgreSQL",
24312435
"slug": "verify-ca-postgresql"
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
---
2+
meta:
3+
title: Setting up and using the pg_cron extension
4+
description: This page explains how to set up and use the pg_cron extension.
5+
content:
6+
h1: Setting up and using the pg_cron extension
7+
paragraph: This page explains how to set up and use the pg_cron extension on Scaleway's Managed Databases for PostgreSQL.
8+
tags: managed-database postgresql pg_cron pg-extensions
9+
dates:
10+
validation: 2025-02-18
11+
posted: 2025-02-18
12+
categories:
13+
- managed-databases
14+
- postgresql-and-mysql
15+
---
16+
17+
The pg_cron extension for PostgreSQL is used to execute periodic tasks. You can schedule SQL tasks, such as queries and data imports, using jobs that run at the intervals you set. On a daily, weekly or monthly basis, for example.
18+
19+
The `pg_cron` extension is available with Scaleway Managed Databases for PostgreSQL. The extension is natively loaded in the `shared_preload_libraries` of the Database Instances by default.
20+
21+
<Macro id="requirements" />
22+
23+
- A Scaleway account logged into the [console](https://console.scaleway.com)
24+
- [Owner](/iam/concepts/#owner) status or [IAM permissions](/iam/concepts/#permission) allowing you to perform actions in the intended Organization
25+
- A [Database Instance](/managed-databases-for-postgresql-and-mysql/how-to/create-a-database/) running a PostgreSQL engine
26+
27+
## Installing pg_cron
28+
29+
<Message type="important">
30+
The `pg_cron` extension can only be installed in the `rdb` database, which is created by default upon Database Instance creation. To run jobs in another database, you can use the [schedule_in_database](#scheduling-jobs-in-other-databases) function.
31+
</Message>
32+
33+
Run the following command to install the extension:
34+
35+
```sql
36+
rdb=> CREATE EXTENSION pg_cron;
37+
CREATE EXTENSION
38+
```
39+
40+
## Configuring pg_cron
41+
42+
To fully use the extension, you must grant read/write rights to the user who will be running the `pg_cron` functions to manage jobs on the database.
43+
44+
<Message type="note">
45+
Refer to the [How to add users to a PostgreSQL or MySQL Database Instance](/managed-databases-for-postgresql-and-mysql/how-to/add-users) documentation for more information.
46+
</Message>
47+
48+
## Scheduling jobs
49+
50+
Jobs allow you to define the SQL command or task you want to run based on a cron schedule.
51+
52+
To schedule jobs, you can run the following command in the SQL client:
53+
```sql
54+
SELECT cron.schedule(
55+
'${JOB_NAME}',
56+
'${SCHEDULE_SPEC}',
57+
$$
58+
${SQL_COMMAND}
59+
$$
60+
);
61+
```
62+
63+
Replace the variables with the corresponding information:
64+
65+
- `${JOB_NAME}` - set a name for the job
66+
- `${SCHEDULE_SPEC}` - the schedule specification in [cron format](/serverless-jobs/reference-content/cron-schedules/)
67+
- `${SQL_COMMAND}` - the SQL command to be executed. Depending on the command, you might need to specify other parameters.
68+
69+
### Examples
70+
71+
**Deleting old data**
72+
73+
You can run the command below to delete old data from the `events` table every Saturday at 3:30am:
74+
75+
```sql
76+
SELECT cron.schedule('30 3 * * 6', $$DELETE FROM events WHERE event_time < now() - interval '1 week'$$);
77+
```
78+
79+
**Scheduling a VACUUM job**
80+
81+
You can run the command below to execute the VACUUM task every day at 10:00am.
82+
83+
```sql
84+
SELECT cron.schedule('nightly-vacuum', '0 10 * * *', 'VACUUM');
85+
```
86+
87+
## Listing jobs
88+
89+
To list all scheduled jobs, you can run the following command:
90+
91+
```sql
92+
SELECT * FROM cron.job;
93+
```
94+
Each job is represented by a record. You can see the following information in the response:
95+
96+
- `jobid` - a unique job ID
97+
- `schedule` - the schedule specification in cron format
98+
- `command` - the SQL command
99+
- `database`, `username`, `nodename`, `nodeport` - connection details
100+
- `active` - whether the job is active or not
101+
- `jobname` - the name of the job
102+
103+
```sql
104+
-[ RECORD 1 ]-------------------------------------------------------------
105+
jobid | 1
106+
schedule | 30 3 * * 6
107+
command | DELETE FROM events WHERE event_time < now() - interval '1 week'
108+
nodename | /var/run/postgresql
109+
nodeport | 5432
110+
database | rdb
111+
username | myuser
112+
active | t
113+
jobname |
114+
-[ RECORD 2 ]-------------------------------------------------------------
115+
jobid | 2
116+
schedule | 0 10 * * *
117+
command | VACUUM
118+
nodename | /var/run/postgresql
119+
nodeport | 5432
120+
database | rdb
121+
username | myuser
122+
active | t
123+
jobname | nightly-vacuum
124+
```
125+
126+
## Unscheduling jobs
127+
128+
To unschedule a job, you can run the following command:
129+
130+
```sql
131+
SELECT cron.unschedule('${JOB_ID}');
132+
```
133+
Replace `${JOB_ID}` with the ID of the job you want to unschedule.
134+
135+
### Examples
136+
137+
To unschedule the jobs set in the previous section, you can run:
138+
139+
```sql
140+
SELECT cron.unschedule(1);
141+
```
142+
143+
or
144+
145+
```sql
146+
SELECT cron.unschedule('nightly-vacuum');
147+
```
148+
149+
## Scheduling jobs in other databases
150+
151+
To schedule a job in another database, you can use the `schedule_in_database` function.
152+
153+
In the example below we create a job to insert values into another table.
154+
155+
```sql
156+
SELECT cron.schedule_in_database('job-in-another-db', '0 12 * * *', 'INSERT INTO public.another_db_table values (now())', 'mydb');
157+
```
158+
<Message type="note">
159+
The `cron.schedule_in_database` function runs jobs as the user who created them. Therefore, you need to connect as said user to execute the job. This function does not allow specifying a different user, as it would require superuser privileges.
160+
</Message>
161+
162+
163+
## Editing jobs
164+
165+
To edit a job, you can use the `alter_job` function.
166+
167+
In the example below we alter an existing job to run in a different database. You must specify the `job_id` and `database`.
168+
169+
```sql
170+
SELECT cron.alter_job(job_id:=3,database:='anotherdb');
171+
```
172+
173+
## Cron specifications
174+
175+
Schedules in `pg_cron` use the standard Cron syntax:
176+
177+
```
178+
┌───────────── min (0 - 59)
179+
│ ┌────────────── hour (0 - 23)
180+
│ │ ┌─────────────── day of month (1 - 31) or last day of the month ($)
181+
│ │ │ ┌──────────────── month (1 - 12)
182+
│ │ │ │ ┌───────────────── day of week (0 - 6) (0 to 6 are Sunday to
183+
│ │ │ │ │ Saturday, or use names; 7 is also Sunday)
184+
│ │ │ │ │
185+
│ │ │ │ │
186+
* * * * *
187+
```
188+
189+
<Message type="tip">
190+
Refer to the [Cron schedules reference](/serverless-jobs/reference-content/cron-schedules/) for a detailed description of the cron format and examples.
191+
</Message>
192+
193+
### How to configure your schedule timezone
194+
195+
The time zone of the `pg_cron` extension can be changed in the advanced settings of the Database Instance. By default, the time zone is set to GMT.
196+
197+
<Message type="note">
198+
The `cron.timezone` setting is only available with PostgreSQL 16.
199+
</Message>
200+
201+
1. Go to the **Advanced settings** of your Database Instance in the Scaleway console.
202+
2. Click <Icon name="edit" />.
203+
3. Click **+ Add parameters**.
204+
4. Select `cron.timezone` in the drop-down.
205+
5. Enter the time zone of your choice.
206+
<Message type="tip">
207+
Refer to the [official PostgreSQL documentation](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-TIMEZONES) for more information about timezone conventions.
208+
</Message>
209+
6. Click <Icon name="validate" /> to validate.
210+
<Message type="note">
211+
The configuration takes a few seconds to be applied. During this time the Database Instance connection remains uninterrupted. However, you must wait until the new configuration is applied to edit your advanced settings again.
212+
</Message>

0 commit comments

Comments
 (0)