task_utils
toolkitx.task_utils
Classes
PersistentTaskQueue
持久化任务队列,使用 SQLite 存储任务状态,支持并发处理和优雅停机。
Examples:
>>> import polars as pl
>>> import tempfile
>>> from pathlib import Path
>>> with tempfile.TemporaryDirectory() as tmpdir:
... db_path = Path(tmpdir) / "tasks.db"
... queue = PersistentTaskQueue(db_path, task_name="test_task")
... queue.setup()
... # 1. 压入任务
... df = pl.DataFrame({
... "batch_id": ["B1", "B1"],
... "input_text": ["text1", "text2"]
... })
... queue.enqueue_dataframe(df)
... # 2. 处理任务
... def my_processor(text: str) -> str:
... return text.upper()
... queue.process(worker_func=my_processor, concurrency=2)
... # 3. 获取结果
... results = queue.get_results().sort("input_text")
... print(results["result"].to_list())
['TEXT1', 'TEXT2']
Source code in toolkitx/task_utils.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | |
Functions
__init__(db_path, task_name, max_retries=3)
初始化持久化任务队列
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str | Path
|
数据库文件路径,用于持久化存储任务状态 |
required |
task_name
|
str
|
任务名称,将作为数据库表名使用 |
required |
max_retries
|
int
|
失败任务的最大重试次数,默认为3次 |
3
|
Attributes:
| Name | Type | Description |
|---|---|---|
db_path |
数据库文件路径 |
|
table_name |
任务表名 |
|
max_retries |
最大重试次数 |
|
db_lock |
数据库操作锁,确保线程安全 |
|
_shutdown_event |
优雅停机事件对象 |
Source code in toolkitx/task_utils.py
enqueue_dataframe(df)
将 Polars DataFrame 压入队列(幂等操作)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Polars DataFrame,必须包含 'batch_id' 和 'input_text' 两列 |
required |
说明: - 使用 INSERT OR IGNORE 语句,重复的 (batch_id, input_text) 组合会被自动过滤 - 所有新任务初始状态为 'pending' - 此方法是幂等的,可以安全地多次调用相同数据
Source code in toolkitx/task_utils.py
get_results(response_model=None)
获取所有已完成任务的结果
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response_model
|
type[BaseModel] | None
|
可选的 Pydantic 模型类型,用于将结果反序列化为强类型对象 如果为 None,结果将被解析为普通字典 |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame,包含所有已完成任务的结果 |
DataFrame
|
|
DataFrame
|
|
说明: - 只返回状态为 'completed' 的任务 - 结果按完成顺序排列 - response_model 必须与 worker_func 返回的数据结构匹配
Source code in toolkitx/task_utils.py
process(worker_func, concurrency=10)
并发调度引擎,处理所有待处理的任务
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
worker_func
|
Callable
|
任务处理函数,接收 input_text 参数,返回处理结果 |
required |
concurrency
|
int
|
并发线程数,默认为10 |
10
|
功能特性: - 支持优雅停机:按下 Ctrl+C 会等待当前正在执行的任务完成 - 实时进度条:显示任务处理进度 - 自动分批:每次从数据库读取最多1000个任务进行处理 - 崩溃恢复:启动时自动重置 processing 状态的任务 - 失败重试:支持自动重试失败的任务
注意: - 此方法会阻塞直到所有任务完成或收到停机信号 - 收到停机信号后,会将正在处理的任务状态重置为 pending - 下次启动时会自动继续处理未完成的任务
Source code in toolkitx/task_utils.py
setup()
初始化数据库表结构、创建索引,并执行崩溃恢复
此方法会: 1. 创建任务表(如果不存在),包含字段:id, batch_id, input_text, status, result, error_msg, retry_count 2. 为 pending 状态的任务创建部分索引,提高查询性能 3. 将所有 processing 状态的任务重置为 pending(处理崩溃恢复) 4. 将未达到最大重试次数的 failed 任务重置为 pending(处理失败恢复)
注意:此方法应在首次使用队列时调用一次,之后每次启动时也建议调用以进行恢复
Source code in toolkitx/task_utils.py
TokenBucket
线程安全的令牌桶限流器
Examples:
Source code in toolkitx/task_utils.py
Functions
with_resilience(qps=None, max_retries=5, base_delay=1.0, max_delay=60.0)
通用 API 韧性装饰器
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
qps
|
float | None
|
每秒最大请求数 (None 表示不限流,依赖默认并发控制) |
None
|
max_retries
|
int
|
遇到网络或 API 错误时的最大退避重试次数 |
5
|
base_delay
|
float
|
退避基础延迟 (秒) |
1.0
|
max_delay
|
float
|
退避最大延迟 (秒) |
60.0
|
Returns:
| Type | Description |
|---|---|
Callable
|
一个装饰器函数,用于为目标函数增加限流和重试能力。 |
Examples:
>>> @with_resilience(qps=100, max_retries=3)
... def fast_func(x):
... return x + 1
>>> fast_func(1)
2