API Reference
docket
docket - A distributed background task system for Python functions.
docket focuses on scheduling future work as seamlessly and efficiently as immediate work.
Agenda
A collection of tasks to be scheduled together on a Docket.
The Agenda allows you to build up a collection of tasks with their arguments, then schedule them all at once using various timing strategies like scattering.
Example
agenda = Agenda() agenda.add(process_item)(item1) agenda.add(process_item)(item2) agenda.add(send_email)(email) await agenda.scatter(docket, over=timedelta(minutes=50))
Source code in src/docket/agenda.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 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 | |
__init__()
__iter__()
__len__()
add(function)
Add a task to the agenda.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
Callable[P, Awaitable[R]] | str
|
The task function or name to add. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., None]
|
A callable that accepts the task arguments and adds them to the agenda. |
Source code in src/docket/agenda.py
clear()
scatter(docket, over, start=None, jitter=None)
async
Scatter the tasks in this agenda over a time period.
Tasks are distributed evenly across the specified time window, optionally with random jitter to prevent thundering herd effects.
If an error occurs during scheduling, some tasks may have already been scheduled successfully before the failure occurred.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docket
|
Docket
|
The Docket to schedule tasks on. |
required |
over
|
timedelta
|
Time period to scatter tasks over (required). |
required |
start
|
datetime | None
|
When to start scattering from. Defaults to now. |
None
|
jitter
|
timedelta | None
|
Maximum random offset to add/subtract from each scheduled time. |
None
|
Returns:
| Type | Description |
|---|---|
list[Execution]
|
List of Execution objects for the scheduled tasks. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If any task name is not registered with the docket. |
ValueError
|
If any task is stricken or 'over' is not positive. |
Source code in src/docket/agenda.py
101 102 103 104 105 106 107 108 109 110 111 112 113 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 | |
ConcurrencyLimit
Bases: Dependency['ConcurrencyLimit']
Configures concurrency limits for task execution.
Can limit concurrency globally for a task, or per specific argument value.
Example:
async def expensive_operation(
concurrency: ConcurrencyLimit = ConcurrencyLimit(max_concurrent=3)
) -> None:
# Only 3 instances of this task will run at a time
...
async def process_customer(
customer_id: int,
concurrency: ConcurrencyLimit = ConcurrencyLimit("customer_id", max_concurrent=1)
) -> None:
# Only one task per customer_id will run at a time
...
async def backup_db(
db_name: str,
concurrency: ConcurrencyLimit = ConcurrencyLimit("db_name", max_concurrent=3)
) -> None:
# Only 3 backup tasks per database name will run at a time
...
Source code in src/docket/dependencies/_concurrency.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 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 | |
concurrency_key
property
Redis key used for tracking concurrency for this specific argument value. Raises RuntimeError if accessed before initialization.
__init__(argument_name=None, max_concurrent=1, scope=None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argument_name
|
str | None
|
The name of the task argument to use for concurrency grouping. If None, limits concurrency for the task function itself. |
None
|
max_concurrent
|
int
|
Maximum number of concurrent tasks |
1
|
scope
|
str | None
|
Optional scope prefix for Redis keys (defaults to docket name) |
None
|
Source code in src/docket/dependencies/_concurrency.py
Cron
Bases: Perpetual
Declare a task that should run on a cron schedule. Cron tasks are automatically
rescheduled for the next matching time after they finish (whether they succeed or
fail). By default, a cron task is scheduled at worker startup with automatic=True.
Unlike Perpetual which schedules based on intervals from the current time, Cron
schedules based on wall-clock time, ensuring tasks run at consistent times regardless
of execution duration or delays.
Supports standard cron expressions and Vixie cron-style keywords (@daily, @hourly, etc.) via the croniter library.
Example:
from zoneinfo import ZoneInfo
@task
async def weekly_report(cron: Cron = Cron("0 9 * * 1")) -> None:
# Runs every Monday at 9:00 AM UTC
...
@task
async def daily_cleanup(cron: Cron = Cron("@daily")) -> None:
# Runs every day at midnight UTC
...
@task
async def morning_standup(
cron: Cron = Cron("0 9 * * 1-5", tz=ZoneInfo("America/Los_Angeles"))
) -> None:
# Runs weekdays at 9:00 AM Pacific (handles DST automatically)
...
Source code in src/docket/dependencies/_cron.py
initial_when
property
Return the next cron time for initial scheduling.
__init__(expression, automatic=True, tz=timezone.utc)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expression
|
str
|
A cron expression string. Supports: - Standard 5-field syntax: "minute hour day month weekday" (e.g., "0 9 * * 1" for Mondays at 9 AM) - Vixie cron keywords: @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly |
required |
automatic
|
bool
|
If set, this task will be automatically scheduled during worker startup and continually through the worker's lifespan. This ensures that the task will always be scheduled despite crashes and other adverse conditions. Automatic tasks must not require any arguments. |
True
|
tz
|
tzinfo
|
Timezone for interpreting the cron expression. Defaults to UTC.
Use |
utc
|
Source code in src/docket/dependencies/_cron.py
on_complete(execution, outcome)
async
Handle completion by scheduling the next execution at the exact cron time.
This overrides Perpetual's on_complete to ensure we hit the exact wall-clock time rather than adjusting for task duration.
Source code in src/docket/dependencies/_cron.py
Docket
Bases: DocketSnapshotMixin
A Docket represents a collection of tasks that may be scheduled for later execution. With a Docket, you can add, replace, and cancel tasks. Example:
@task
async def my_task(greeting: str, recipient: str) -> None:
print(f"{greeting}, {recipient}!")
async with Docket() as docket:
docket.add(my_task)("Hello", recipient="world")
Source code in src/docket/docket.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 | |
prefix
property
Return the key prefix for this docket.
All Redis keys for this docket are prefixed with this value.
For Redis Cluster mode, returns a hash-tagged prefix like "{myapp}" to ensure all keys hash to the same slot.
results_collection
property
Return the collection name for result storage.
__init__(name='docket', url='redis://localhost:6379/0', heartbeat_interval=timedelta(seconds=2), missed_heartbeats=5, execution_ttl=timedelta(minutes=15), result_storage=None, enable_internal_instrumentation=False)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the docket. |
'docket'
|
url
|
str
|
The URL of the Redis server or in-memory backend. For example: - "redis://localhost:6379/0" - "redis://user:password@localhost:6379/0" - "redis://user:password@localhost:6379/0?ssl=true" - "rediss://localhost:6379/0" - "unix:///path/to/redis.sock" - "memory://" (in-memory backend for testing) |
'redis://localhost:6379/0'
|
heartbeat_interval
|
timedelta
|
How often workers send heartbeat messages to the docket. |
timedelta(seconds=2)
|
missed_heartbeats
|
int
|
How many heartbeats a worker can miss before it is considered dead. |
5
|
execution_ttl
|
timedelta
|
How long to keep completed or failed execution state records in Redis before they expire. Defaults to 15 minutes. |
timedelta(minutes=15)
|
enable_internal_instrumentation
|
bool
|
Whether to enable OpenTelemetry spans for internal Redis polling operations like strike stream monitoring. Defaults to False. |
False
|
Source code in src/docket/docket.py
add(function, when=None, key=None)
Add a task to the Docket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
Callable[P, Awaitable[R]] | str
|
The task to add. |
required |
when
|
datetime | None
|
The time to schedule the task. |
None
|
key
|
str | None
|
The key to schedule the task under. |
None
|
Source code in src/docket/docket.py
cancel(key)
async
Cancel a previously scheduled task on the Docket.
If the task is scheduled (in the queue or stream), it will be removed. If the task is currently running, a cancellation signal will be sent to the worker, which will attempt to cancel the asyncio task. This is best-effort: if the task completes before the signal is processed, the cancellation will have no effect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key of the task to cancel. |
required |
Source code in src/docket/docket.py
cancel_channel(task_key)
clear()
async
Clear all queued and scheduled tasks from the docket.
This removes all tasks from the stream (immediate tasks) and queue (scheduled tasks), along with their associated parked data. Running tasks are not affected.
Returns:
| Type | Description |
|---|---|
int
|
The total number of tasks that were cleared. |
Source code in src/docket/docket.py
get_execution(key)
async
Get a task Execution from the Docket by its key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The task key. |
required |
Returns:
| Type | Description |
|---|---|
Execution | None
|
The Execution if found, None if the key doesn't exist. |
Example
Claim check pattern: schedule a task, save the key,
then retrieve the execution later to check status or get results
execution = await docket.add(my_task, key="important-task")(args) task_key = execution.key
Later, retrieve the execution by key
execution = await docket.get_execution(task_key) if execution: await execution.get_result()
Source code in src/docket/docket.py
key(suffix)
Return a Redis key with the docket prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suffix
|
str
|
The key suffix (e.g., "queue", "stream", "runs:task-123") |
required |
Returns:
| Type | Description |
|---|---|
str
|
Full Redis key like "docket:queue" or "docket:stream" |
Source code in src/docket/docket.py
register(function, names=None)
Register a task with the Docket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
TaskFunction
|
The task to register. |
required |
names
|
list[str] | None
|
Names to register the task under. Defaults to [function.name]. |
None
|
Source code in src/docket/docket.py
register_collection(collection_path)
Register a collection of tasks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection_path
|
str
|
A path in the format "module:collection". |
required |
Source code in src/docket/docket.py
replace(function, when, key)
Replace a previously scheduled task on the Docket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
Callable[P, Awaitable[R]] | str
|
The task to replace. |
required |
when
|
datetime
|
The time to schedule the task. |
required |
key
|
str
|
The key to schedule the task under. |
required |
Source code in src/docket/docket.py
restore(function=None, parameter=None, operator='==', value=None)
async
Restore a previously stricken task to the Docket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
Callable[P, Awaitable[R]] | str | None
|
The task to restore (function or name), or None for all tasks. |
None
|
parameter
|
str | None
|
The parameter to restore on, or None for entire task. |
None
|
operator
|
Operator | LiteralOperator
|
The comparison operator to use. |
'=='
|
value
|
Hashable | None
|
The value to restore on. |
None
|
Source code in src/docket/docket.py
runs_key(task_key)
strike(function=None, parameter=None, operator='==', value=None)
async
Strike a task from the Docket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
Callable[P, Awaitable[R]] | str | None
|
The task to strike (function or name), or None for all tasks. |
None
|
parameter
|
str | None
|
The parameter to strike on, or None for entire task. |
None
|
operator
|
Operator | LiteralOperator
|
The comparison operator to use. |
'=='
|
value
|
Hashable | None
|
The value to strike on. |
None
|
Source code in src/docket/docket.py
wait_for_strikes_loaded()
async
Wait for all existing strikes to be loaded from the stream.
This method blocks until the strike monitor has completed its initial non-blocking read of all existing strike messages. Call this before making decisions that depend on the current strike state, such as scheduling automatic perpetual tasks.
Source code in src/docket/docket.py
Execution
Represents a task execution with state management and progress tracking.
Combines task invocation metadata (function, args, when, etc.) with Redis-backed lifecycle state tracking and user-reported progress.
Source code in src/docket/execution.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 | |
args
property
Positional arguments for the task.
docket
property
Parent docket instance.
function
property
Task function to execute.
function_name
property
Name of the task function (from message, may differ from function.name for fallback tasks).
generation
property
Scheduling generation counter for supersession detection.
key
property
Unique task identifier.
kwargs
property
Keyword arguments for the task.
redelivered
property
Whether this message was redelivered.
trace_context
property
OpenTelemetry trace context.
claim(worker)
async
Atomically check supersession and claim task in a single round-trip.
This consolidates worker operations when claiming a task into a single atomic Lua script that: - Checks if the task has been superseded by a newer generation - Sets state to RUNNING with worker name and timestamp - Initializes progress tracking (current=0, total=100) - Deletes known/stream_id fields to allow task rescheduling - Cleans up legacy keys for backwards compatibility
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
worker
|
str
|
Name of the worker claiming the task |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the task was claimed, False if it was superseded. |
Source code in src/docket/execution.py
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 | |
get_result(*, timeout=None, deadline=None)
async
Retrieve the result of this task execution.
If the execution is not yet complete, this method will wait using pub/sub for state updates until completion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
timedelta | None
|
Optional duration to wait before giving up. If None and deadline is None, waits indefinitely. |
None
|
deadline
|
datetime | None
|
Optional absolute datetime when to stop waiting. If None and timeout is None, waits indefinitely. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The result of the task execution, or None if the task returned None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both timeout and deadline are provided |
Exception
|
If the task failed, raises the stored exception |
TimeoutError
|
If timeout/deadline is reached before execution completes |
Source code in src/docket/execution.py
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 | |
is_superseded()
async
Check whether a newer schedule has superseded this execution.
Compares this execution's generation against the current generation stored in the runs hash. If the stored generation is strictly greater, this execution has been superseded by a newer schedule() call.
Generation 0 means the message predates generation tracking (e.g. it was moved from queue to stream by an older worker's scheduler that doesn't pass through the generation field). These are never considered superseded since we can't tell.
Source code in src/docket/execution.py
mark_as_cancelled()
async
mark_as_completed(result_key=None)
async
Mark task as completed successfully.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result_key
|
str | None
|
Optional key where the task result is stored |
None
|
Source code in src/docket/execution.py
mark_as_failed(error=None, result_key=None)
async
Mark task as failed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
str | None
|
Optional error message describing the failure |
None
|
result_key
|
str | None
|
Optional key where the exception is stored |
None
|
Source code in src/docket/execution.py
schedule(replace=False, reschedule_message=None)
async
Schedule this task atomically in Redis.
This performs an atomic operation that: - Adds the task to the stream (immediate) or queue (future) - Writes the execution state record - Tracks metadata for later cancellation
Usage patterns: - Normal add: schedule(replace=False) - Replace existing: schedule(replace=True) - Reschedule from stream: schedule(reschedule_message=message_id) This atomically acknowledges and deletes the stream message, then reschedules the task to the queue. Prevents both task loss and duplicate execution when rescheduling tasks (e.g., due to concurrency limits).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
replace
|
bool
|
If True, replaces any existing task with the same key. If False, raises an error if the task already exists. |
False
|
reschedule_message
|
RedisMessageID | None
|
If provided, atomically acknowledges and deletes this stream message ID before rescheduling the task to the queue. Used when a task needs to be rescheduled from an active stream message. |
None
|
Source code in src/docket/execution.py
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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 | |
subscribe()
async
Subscribe to both state and progress updates for this task.
Emits the current state as the first event, then subscribes to real-time state and progress updates via Redis pub/sub.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[StateEvent | ProgressEvent, None]
|
Dict containing state or progress update events with a 'type' field: |
AsyncGenerator[StateEvent | ProgressEvent, None]
|
|
AsyncGenerator[StateEvent | ProgressEvent, None]
|
|
Source code in src/docket/execution.py
sync()
async
Synchronize instance attributes with current execution data from Redis.
Updates self.state, execution metadata, and progress data from Redis. Sets attributes to None if no data exists.
Source code in src/docket/execution.py
ExecutionCancelled
ExecutionState
Bases: Enum
Lifecycle states for task execution.
Source code in src/docket/execution.py
CANCELLED = 'cancelled'
class-attribute
instance-attribute
Task was explicitly cancelled before completion.
COMPLETED = 'completed'
class-attribute
instance-attribute
Task execution finished successfully.
FAILED = 'failed'
class-attribute
instance-attribute
Task execution failed.
QUEUED = 'queued'
class-attribute
instance-attribute
Task has been moved to the stream and is ready to be claimed by a worker.
RUNNING = 'running'
class-attribute
instance-attribute
Task is currently being executed by a worker.
SCHEDULED = 'scheduled'
class-attribute
instance-attribute
Task is scheduled and waiting in the queue for its execution time.
ExponentialRetry
Bases: Retry
Configures exponential retries for a task. You can specify the total number
of attempts (or None to retry indefinitely), and the minimum and maximum delays
between attempts.
Example:
Source code in src/docket/dependencies/_retry.py
__init__(attempts=1, minimum_delay=timedelta(seconds=1), maximum_delay=timedelta(seconds=64))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attempts
|
int | None
|
The total number of attempts to make. If |
1
|
minimum_delay
|
timedelta
|
The minimum delay between attempts. |
timedelta(seconds=1)
|
maximum_delay
|
timedelta
|
The maximum delay between attempts. |
timedelta(seconds=64)
|
Source code in src/docket/dependencies/_retry.py
Logged
Bases: Annotation
Instructs docket to include arguments to this parameter in the log.
If length_only is True, only the length of the argument will be included in
the log.
Example:
@task
def setup_new_customer(
customer_id: Annotated[int, Logged],
addresses: Annotated[list[Address], Logged(length_only=True)],
password: str,
) -> None:
...
In the logs, you's see the task referenced as:
Source code in src/docket/annotations.py
Perpetual
Bases: CompletionHandler['Perpetual']
Declare a task that should be run perpetually. Perpetual tasks are automatically
rescheduled for the future after they finish (whether they succeed or fail). A
perpetual task can be scheduled at worker startup with the automatic=True.
Example:
Source code in src/docket/dependencies/_perpetual.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 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 | |
initial_when
property
Return None to schedule for immediate execution at worker startup.
__init__(every=timedelta(0), automatic=False)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
every
|
timedelta
|
The target interval between task executions. |
timedelta(0)
|
automatic
|
bool
|
If set, this task will be automatically scheduled during worker startup and continually through the worker's lifespan. This ensures that the task will always be scheduled despite crashes and other adverse conditions. Automatic tasks must not require any arguments. |
False
|
Source code in src/docket/dependencies/_perpetual.py
after(delay)
at(when)
on_complete(execution, outcome)
async
Handle completion by scheduling the next execution.
Source code in src/docket/dependencies/_perpetual.py
Progress
Bases: Dependency['Progress']
A dependency to report progress updates for the currently executing task.
Tasks can use this to report their current progress (current/total values) and status messages to external observers.
Example:
@task
async def process_records(records: list, progress: Progress = Progress()) -> None:
await progress.set_total(len(records))
for i, record in enumerate(records):
await process(record)
await progress.increment()
await progress.set_message(f"Processed {record.id}")
Source code in src/docket/dependencies/_progress.py
current
property
Current progress value.
message
property
User-provided status message.
total
property
Total/target value for progress tracking.
increment(amount=1)
async
Atomically increment the current progress value.
set_message(message)
async
Update the progress status message.
set_total(total)
async
Set the total/target value for progress tracking.
Retry
Bases: FailureHandler['Retry']
Configures linear retries for a task. You can specify the total number of
attempts (or None to retry indefinitely), and the delay between attempts.
Example:
Source code in src/docket/dependencies/_retry.py
__init__(attempts=1, delay=timedelta(0))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attempts
|
int | None
|
The total number of attempts to make. If |
1
|
delay
|
timedelta
|
The delay between attempts. |
timedelta(0)
|
Source code in src/docket/dependencies/_retry.py
after(delay)
at(when)
Request a retry at the given time.
handle_failure(execution, outcome)
async
Handle failure by scheduling a retry if attempts remain.
Source code in src/docket/dependencies/_retry.py
StrikeList
A strike list that manages conditions for blocking task execution.
When a URL is provided, the strike list will connect to Redis and monitor a stream for strike/restore instructions. External processes (like Docket) can issue strikes, and all StrikeList instances listening to the same stream will receive and apply those updates.
Example using context manager with Redis
async with StrikeList(url="redis://localhost:6379/0", name="my-docket") as strikes: # External process issues: await docket.strike("my_task", "customer_id", "==", "blocked")
if strikes.is_stricken({"customer_id": "blocked"}):
print("Customer is blocked")
Example with Docket (managed internally): async with Docket(name="my-docket", url="redis://localhost:6379/0") as docket: # Docket manages its own StrikeList internally await docket.strike(None, "customer_id", "==", "blocked")
Example using explicit connect/close: strikes = StrikeList(url="redis://localhost:6379/0", name="my-docket") await strikes.connect() try: if strikes.is_stricken({"customer_id": "blocked"}): print("Customer is blocked") finally: await strikes.close()
Example without Redis (local-only): strikes = StrikeList() # No URL = no Redis connection strikes.update(Strike(None, "customer_id", Operator.EQUAL, "blocked")) if strikes.is_stricken({"customer_id": "blocked"}): print("Customer is blocked")
Source code in src/docket/strikelist.py
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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 | |
prefix
property
Return the key prefix for this strike list.
All Redis keys for this strike list are prefixed with this value.
For Redis Cluster mode, returns a hash-tagged prefix like "{myapp}" to ensure all keys hash to the same slot.
strike_key
property
Redis stream key for strike instructions.
__aenter__()
async
Async context manager entry - connects to Redis if URL provided.
Source code in src/docket/strikelist.py
__aexit__(exc_type, exc_value, traceback)
async
Async context manager exit - closes Redis connection.
Source code in src/docket/strikelist.py
__init__(url=None, name='strikelist', enable_internal_instrumentation=False)
Initialize a StrikeList.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str | None
|
Redis connection URL. Use "memory://" for in-memory testing. If None, no Redis connection is made (local-only mode). |
None
|
name
|
str
|
Name used as prefix for Redis keys (should match the Docket name if you want to receive strikes from that Docket). |
'strikelist'
|
enable_internal_instrumentation
|
bool
|
If True, allows OpenTelemetry spans for internal Redis operations. Default False suppresses these spans. |
False
|
Source code in src/docket/strikelist.py
add_condition(condition)
Adds a temporary condition that indicates an execution is stricken.
is_stricken(target)
Check if a target matches any strike condition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Execution | Mapping[str, Any]
|
Either an Execution object (for Docket/Worker use) or a dictionary of parameter names to values (for standalone use). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if any parameter matches a strike condition. |
Source code in src/docket/strikelist.py
remove_condition(condition)
Removes a temporary condition that indicates an execution is stricken.
Source code in src/docket/strikelist.py
restore(function=None, parameter=None, operator='==', value=None)
async
Restore a previously issued strike.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
str | None
|
Task function name to restore, or None for all tasks. |
None
|
parameter
|
str | None
|
Parameter name to match, or None for entire task. |
None
|
operator
|
Operator | LiteralOperator
|
Comparison operator for the value. |
'=='
|
value
|
Hashable | None
|
Value to compare against. |
None
|
Source code in src/docket/strikelist.py
send_instruction(instruction)
async
Send a strike instruction to Redis and update local state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instruction
|
StrikeInstruction
|
The Strike or Restore instruction to send. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If not connected to Redis. |
Source code in src/docket/strikelist.py
strike(function=None, parameter=None, operator='==', value=None)
async
Issue a strike to block matching tasks or parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
str | None
|
Task function name to strike, or None for all tasks. |
None
|
parameter
|
str | None
|
Parameter name to match, or None for entire task. |
None
|
operator
|
Operator | LiteralOperator
|
Comparison operator for the value. |
'=='
|
value
|
Hashable | None
|
Value to compare against. |
None
|
Source code in src/docket/strikelist.py
wait_for_strikes_loaded()
async
Wait for all existing strikes to be loaded from the stream.
This method blocks until the strike monitor has completed its initial non-blocking read of all existing strike messages. Call this before making decisions that depend on the current strike state.
If not connected to Redis (local-only mode), returns immediately.
Source code in src/docket/strikelist.py
Timeout
Bases: Runtime['Timeout']
Configures a timeout for a task. You can specify the base timeout, and the task will be cancelled if it exceeds this duration. The timeout may be extended within the context of a single running task.
Example:
Source code in src/docket/dependencies/_timeout.py
__init__(base)
extend(by=None)
Extend the timeout by a given duration. If no duration is provided, the base timeout will be used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
by
|
timedelta | None
|
The duration to extend the timeout by. |
None
|
Source code in src/docket/dependencies/_timeout.py
remaining()
run(execution, function, args, kwargs)
async
Execute the function with timeout enforcement.
Source code in src/docket/dependencies/_timeout.py
Worker
A Worker executes tasks on a Docket. You may run as many workers as you like to work a single Docket.
Example:
Source code in src/docket/worker.py
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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 | |
run(docket_name='docket', url='redis://localhost:6379/0', name=None, concurrency=10, redelivery_timeout=timedelta(minutes=5), reconnection_delay=timedelta(seconds=5), minimum_check_interval=timedelta(milliseconds=100), scheduling_resolution=timedelta(milliseconds=250), schedule_automatic_tasks=True, enable_internal_instrumentation=False, until_finished=False, healthcheck_port=None, metrics_port=None, tasks=['docket.tasks:standard_tasks'], fallback_task=None)
async
classmethod
Run a worker as the main entry point (CLI).
This method installs signal handlers for graceful shutdown since it assumes ownership of the event loop. When embedding Docket in another framework (e.g., FastAPI with uvicorn), use Worker.run_forever() or Worker.run_until_finished() directly - those methods do not install signal handlers and rely on the framework to handle shutdown signals.
Source code in src/docket/worker.py
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 | |
run_at_most(iterations_by_key)
async
Run the worker until there are no more tasks to process, but limit specified task keys to a maximum number of iterations.
This is particularly useful for testing self-perpetuating tasks that would otherwise run indefinitely.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iterations_by_key
|
Mapping[str, int]
|
Maps task keys to their maximum allowed executions |
required |
Source code in src/docket/worker.py
run_forever()
async
CurrentDocket()
CurrentExecution()
CurrentWorker()
Depends(dependency)
Include a user-defined function as a dependency. Dependencies may be: - Synchronous functions returning a value - Asynchronous functions returning a value (awaitable) - Synchronous context managers (using @contextmanager) - Asynchronous context managers (using @asynccontextmanager)
If a dependency returns a context manager, it will be entered and exited around the task, giving an opportunity to control the lifetime of a resource.
Important: Synchronous dependencies should NOT include blocking I/O operations (file access, network calls, database queries, etc.). Use async dependencies for any I/O. Sync dependencies are best for: - Pure computations - In-memory data structure access - Configuration lookups from memory - Non-blocking transformations
Examples:
# Sync dependency - pure computation, no I/O
def get_config() -> dict:
# Access in-memory config, no I/O
return {"api_url": "https://api.example.com", "timeout": 30}
# Sync dependency - compute value from arguments
def build_query_params(
user_id: int = TaskArgument(),
config: dict = Depends(get_config)
) -> dict:
# Pure computation, no I/O
return {"user_id": user_id, "timeout": config["timeout"]}
# Async dependency - I/O operations
async def get_user(user_id: int = TaskArgument()) -> User:
# Network I/O - must be async
return await fetch_user_from_api(user_id)
# Async context manager - I/O resource management
from contextlib import asynccontextmanager
@asynccontextmanager
async def get_db_connection():
# I/O operations - must be async
conn = await db.connect()
try:
yield conn
finally:
await conn.close()
@task
async def my_task(
params: dict = Depends(build_query_params),
user: User = Depends(get_user),
db: Connection = Depends(get_db_connection),
) -> None:
await db.execute("UPDATE users SET ...", params)
Source code in src/docket/dependencies/_functional.py
TaskArgument(parameter=None, optional=False)
A dependency to access a argument of the currently executing task. This is often useful in dependency functions so they can access the arguments of the task they are injected into.
Example:
async def customer_name(customer_id: int = TaskArgument()) -> str:
...look up the customer's name by ID...
return "John Doe"
@task
async def greet_customer(customer_id: int, name: str = Depends(customer_name)) -> None:
print(f"Hello, {name}!")
Source code in src/docket/dependencies/_contextual.py
TaskKey()
A dependency to access the key of the currently executing task.
Example:
Source code in src/docket/dependencies/_contextual.py
TaskLogger()
A dependency to access a logger for the currently executing task. The logger will automatically inject contextual information such as the worker and docket name, the task key, and the current execution attempt number.
Example:
@task
async def my_task(logger: "LoggerAdapter[Logger]" = TaskLogger()) -> None:
logger.info("Hello, world!")