0
# Job Scheduling
1
2
RQ Scheduler provides multiple methods for scheduling jobs to run at specific times or intervals. All scheduling methods support comprehensive job configuration options and return RQ Job instances that can be tracked and managed.
3
4
## Capabilities
5
6
### Absolute Time Scheduling
7
8
Schedule jobs to run at specific datetime values. All times should be in UTC for consistent behavior across timezones.
9
10
```python { .api }
11
def enqueue_at(self, scheduled_time, func, *args, **kwargs):
12
"""
13
Schedule a job to run at a specific datetime.
14
15
Parameters:
16
- scheduled_time: datetime, when to run the job (should be UTC)
17
- func: callable, function to execute
18
- *args: arguments to pass to func
19
- **kwargs: keyword arguments and scheduling options
20
21
Scheduling Options (passed as **kwargs):
22
- timeout: int, job timeout in seconds
23
- job_id: str, custom job ID
24
- job_ttl: int, job time-to-live in seconds
25
- job_result_ttl: int, result storage time in seconds
26
- job_description: str, human-readable job description
27
- depends_on: Job or job_id, job dependency
28
- meta: dict, custom metadata
29
- queue_name: str, target queue name (overrides scheduler default)
30
- on_success: callable, success callback
31
- on_failure: callable, failure callback
32
- at_front: bool, enqueue at front of queue when scheduled
33
34
Returns:
35
Job instance with scheduled status
36
"""
37
```
38
39
**Usage Examples:**
40
41
```python
42
from datetime import datetime
43
from rq_scheduler import Scheduler
44
from redis import Redis
45
46
scheduler = Scheduler(connection=Redis())
47
48
# Basic scheduling
49
job = scheduler.enqueue_at(
50
datetime(2025, 12, 31, 23, 59),
51
print_message,
52
"Happy New Year!"
53
)
54
55
# With options
56
job = scheduler.enqueue_at(
57
datetime(2025, 6, 15, 10, 30),
58
process_data,
59
data_id=12345,
60
timeout=300,
61
job_description="Monthly data processing",
62
meta={'department': 'analytics'},
63
queue_name='high_priority'
64
)
65
```
66
67
### Relative Time Scheduling
68
69
Schedule jobs to run after a specific time delay from the current moment.
70
71
```python { .api }
72
def enqueue_in(self, time_delta, func, *args, **kwargs):
73
"""
74
Schedule a job to run after a time delay.
75
76
Parameters:
77
- time_delta: timedelta, delay before job execution
78
- func: callable, function to execute
79
- *args: arguments to pass to func
80
- **kwargs: keyword arguments and scheduling options (same as enqueue_at)
81
82
Returns:
83
Job instance with scheduled status
84
"""
85
```
86
87
**Usage Examples:**
88
89
```python
90
from datetime import timedelta
91
92
# Run in 10 minutes
93
scheduler.enqueue_in(timedelta(minutes=10), send_reminder, user_id=123)
94
95
# Run in 2 hours with retry logic
96
scheduler.enqueue_in(
97
timedelta(hours=2),
98
backup_database,
99
timeout=1800,
100
on_failure=handle_backup_failure
101
)
102
103
# Run tomorrow
104
scheduler.enqueue_in(timedelta(days=1), daily_report)
105
```
106
107
### Periodic Job Scheduling
108
109
Schedule jobs to repeat at regular intervals. Supports limited repetitions or infinite recurring jobs.
110
111
```python { .api }
112
def schedule(self, scheduled_time, func, args=None, kwargs=None, interval=None,
113
repeat=None, result_ttl=None, ttl=None, timeout=None, id=None,
114
description=None, queue_name=None, meta=None, depends_on=None,
115
on_success=None, on_failure=None, at_front=None):
116
"""
117
Schedule a periodic or repeated job.
118
119
Parameters:
120
- scheduled_time: datetime, first execution time
121
- func: callable, function to execute
122
- args: tuple, positional arguments for func
123
- kwargs: dict, keyword arguments for func
124
- interval: int, seconds between repetitions
125
- repeat: int, number of times to repeat (None for infinite)
126
- result_ttl: int, result storage time (-1 for periodic jobs default)
127
- ttl: int, job time-to-live
128
- timeout: int, job timeout in seconds
129
- id: str, custom job ID
130
- description: str, job description
131
- queue_name: str, target queue name
132
- meta: dict, custom metadata
133
- depends_on: Job or job_id, job dependency
134
- on_success: callable, success callback
135
- on_failure: callable, failure callback
136
- at_front: bool, enqueue at front of queue
137
138
Returns:
139
Job instance configured for repetition
140
141
Raises:
142
ValueError: if repeat is specified without interval
143
"""
144
```
145
146
**Usage Examples:**
147
148
```python
149
from datetime import datetime, timedelta
150
151
# Run every hour starting in 5 minutes
152
scheduler.schedule(
153
scheduled_time=datetime.utcnow() + timedelta(minutes=5),
154
func=check_system_health,
155
interval=3600 # 1 hour
156
)
157
158
# Run every 30 minutes, but only 10 times
159
scheduler.schedule(
160
scheduled_time=datetime.utcnow() + timedelta(minutes=1),
161
func=poll_api,
162
args=['https://api.example.com/status'],
163
interval=1800, # 30 minutes
164
repeat=10
165
)
166
167
# Daily backup at 2 AM
168
scheduler.schedule(
169
scheduled_time=datetime(2025, 1, 2, 2, 0), # Tomorrow at 2 AM
170
func=perform_backup,
171
kwargs={'backup_type': 'incremental'},
172
interval=86400, # Daily
173
description="Daily incremental backup"
174
)
175
```
176
177
### Cron-Style Scheduling
178
179
Schedule jobs using cron expressions for complex recurring patterns. Supports standard cron syntax with optional timezone handling.
180
181
```python { .api }
182
def cron(self, cron_string, func, args=None, kwargs=None, repeat=None,
183
queue_name=None, result_ttl=-1, ttl=None, id=None, timeout=None,
184
description=None, meta=None, use_local_timezone=False, depends_on=None,
185
on_success=None, on_failure=None, at_front=False):
186
"""
187
Schedule a job using cron syntax.
188
189
Parameters:
190
- cron_string: str, cron expression (minute hour day month weekday)
191
- func: callable, function to execute
192
- args: tuple, positional arguments for func
193
- kwargs: dict, keyword arguments for func
194
- repeat: int, number of times to repeat (None for infinite)
195
- queue_name: str, target queue name
196
- result_ttl: int, result storage time (default -1)
197
- ttl: int, job time-to-live
198
- id: str, custom job ID
199
- timeout: int, job timeout in seconds
200
- description: str, job description
201
- meta: dict, custom metadata
202
- use_local_timezone: bool, use local timezone instead of UTC
203
- depends_on: Job or job_id, job dependency
204
- on_success: callable, success callback
205
- on_failure: callable, failure callback
206
- at_front: bool, enqueue at front of queue
207
208
Returns:
209
Job instance configured for cron scheduling
210
"""
211
```
212
213
**Usage Examples:**
214
215
```python
216
# Every weekday at 9 AM
217
scheduler.cron(
218
"0 9 * * 1-5", # minute=0, hour=9, any day, any month, Mon-Fri
219
send_daily_report,
220
description="Weekday morning report"
221
)
222
223
# Every 15 minutes
224
scheduler.cron("*/15 * * * *", check_queue_status)
225
226
# First day of every month at midnight
227
scheduler.cron(
228
"0 0 1 * *",
229
monthly_cleanup,
230
args=['logs', 'temp_files'],
231
description="Monthly cleanup task"
232
)
233
234
# Every Sunday at 3 AM, but only run 12 times (quarterly for 3 years)
235
scheduler.cron(
236
"0 3 * * 0",
237
quarterly_report,
238
repeat=12,
239
timeout=7200 # 2 hours
240
)
241
242
# Using local timezone
243
scheduler.cron(
244
"30 14 * * *", # 2:30 PM local time
245
afternoon_task,
246
use_local_timezone=True
247
)
248
```
249
250
## Cron Expression Format
251
252
Cron expressions use the standard five-field format:
253
254
```
255
* * * * *
256
| | | | |
257
| | | | └─── day of week (0-7, Sunday = 0 or 7)
258
| | | └───── month (1-12)
259
| | └─────── day of month (1-31)
260
| └───────── hour (0-23)
261
└─────────── minute (0-59)
262
```
263
264
**Special Characters:**
265
- `*` - any value
266
- `,` - value list separator (e.g., `1,3,5`)
267
- `-` - range of values (e.g., `1-5`)
268
- `/` - step values (e.g., `*/15` for every 15 minutes)
269
270
**Common Patterns:**
271
- `0 * * * *` - every hour at minute 0
272
- `0 0 * * *` - daily at midnight
273
- `0 0 * * 0` - weekly on Sunday at midnight
274
- `0 0 1 * *` - monthly on the 1st at midnight
275
- `*/30 * * * *` - every 30 minutes