File size: 53,079 Bytes
25f22bf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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 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 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 |
======================== CODE SNIPPETS ======================== TITLE: Celery Beat Schedule Setting DESCRIPTION: The `beat_schedule` setting defines the periodic task schedule used by `celery beat`. It defaults to an empty mapping (`{}`) and refers to `beat-entries` for details. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_193 LANGUAGE: APIDOC CODE: ``` beat_schedule: Default: {} Description: The periodic task schedule used by `celery beat`. ``` ---------------------------------------- TITLE: Configure Celery Broadcast Routing with Beat Schedule DESCRIPTION: This Python example illustrates how to integrate broadcast routing with `celery beat` schedules. It shows how to define a periodic task that uses a broadcast exchange, ensuring the scheduled task is sent to every worker. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/routing.rst#_snippet_47 LANGUAGE: python CODE: ``` from kombu.common import Broadcast from celery.schedules import crontab app.conf.task_queues = (Broadcast('broadcast_tasks'),) app.conf.beat_schedule = { 'test-task': { 'task': 'tasks.reload_cache', 'schedule': crontab(minute=0, hour='*/3'), 'options': {'exchange': 'broadcast_tasks'} }, } ``` ---------------------------------------- TITLE: Celery Solar Schedule Configuration Example DESCRIPTION: Demonstrates how to configure a Celery beat schedule to execute a task at a specific solar event (e.g., sunset) for a given latitude and longitude using the `celery.schedules.solar` function. This example schedules a task to run at sunset in Melbourne. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_9 LANGUAGE: python CODE: ``` from celery.schedules import solar app.conf.beat_schedule = { # Executes at sunset in Melbourne 'add-at-melbourne-sunset': { 'task': 'tasks.add', 'schedule': solar('sunset', -37.81753, 144.96715), 'args': (16, 16), }, } ``` ---------------------------------------- TITLE: Celery Crontab Schedule Expression Examples DESCRIPTION: This section provides various examples of `celery.schedules.crontab` expressions, illustrating how to define different periodic schedules, from every minute to specific hours and days of the week. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_7 LANGUAGE: APIDOC CODE: ``` crontab(): Execute every minute. crontab(minute=0, hour=0): Execute daily at midnight. crontab(minute=0, hour='*/3'): Execute every three hours (midnight, 3am, 6am, 9am, noon, 3pm, 6pm, 9pm). crontab(minute=0, hour='0,3,6,9,12,15,18,21'): Same as previous. crontab(minute='*/15'): Execute every 15 minutes. crontab(day_of_week='sunday'): Execute every minute (!) on Sundays. crontab(minute='*', hour='*', day_of_week='sun'): Same as previous. crontab(minute='*/10', hour='3,17,22', day_of_week='thu,fri'): Execute every ten minutes, but only between 3-4 am, 5-6 pm, and 10-11 pm on Thursdays or Fridays. crontab(minute=0, hour='*/2,*/3'): Execute every even hour, and every hour divisible by three. ``` ---------------------------------------- TITLE: Celery Task.apply_async Method for Scheduled Execution DESCRIPTION: The `Task.apply_async` method allows scheduling a task to execute at a specific future time using the `eta` argument. While useful for short-term scheduling, using distant `eta` times is discouraged; for long-term or recurring schedules, Celery's periodic tasks (via `celery-beat`) are preferred. SOURCE: https://github.com/celery/celery/blob/main/docs/faq.rst#_snippet_21 LANGUAGE: APIDOC CODE: ``` Task.apply_async(eta=datetime): Parameters: eta (datetime): The exact time at which the task should be executed. Purpose: Schedule a task to run at a specific future time. Note: Distant `eta` times are not recommended; prefer periodic tasks for such cases. ``` ---------------------------------------- TITLE: Configure Celery Beat Crontab Schedule in Python DESCRIPTION: This Python code demonstrates how to configure a periodic task using `celery.schedules.crontab` within the `app.conf.beat_schedule` dictionary. It provides an example of scheduling a task to run every Monday morning at 7:30 a.m. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_6 LANGUAGE: Python CODE: ``` from celery.schedules import crontab app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'add-every-monday-morning': { 'task': 'tasks.add', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (16, 16), }, } ``` ---------------------------------------- TITLE: Celery Beat Scheduler Setting DESCRIPTION: The `beat_scheduler` setting specifies the default scheduler class for Celery Beat. It defaults to `"celery.beat:PersistentScheduler"` but can be set to other schedulers like `"django_celery_beat.schedulers:DatabaseScheduler"` for extensions. It can also be configured via the `celery beat -S` argument. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_194 LANGUAGE: APIDOC CODE: ``` beat_scheduler: Default: "celery.beat:PersistentScheduler" Description: The default scheduler class. May be set to `django_celery_beat.schedulers:DatabaseScheduler` or via `celery beat -S` argument. ``` ---------------------------------------- TITLE: Define Celery Periodic Tasks with Crontab Schedules DESCRIPTION: This snippet demonstrates how to define periodic tasks in Celery using the `@periodic_task` decorator and `crontab` for scheduling. It shows examples for daily, weekly (Monday), and hourly execution intervals. These tasks run automatically based on the specified schedule. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_3 LANGUAGE: Python CODE: ``` @periodic_task(run_every=crontab(hour=7, minute=30)) def every_morning(): print('Runs every morning at 7:30a.m') @periodic_task(run_every=crontab(hour=7, minute=30, day_of_week='mon')) def every_monday_morning(): print('Run every monday morning at 7:30a.m') @periodic_task(run_every=crontab(minutes=30)) def every_hour(): print('Runs every hour on the clock (e.g., 1:30, 2:30, 3:30 etc.).') ``` ---------------------------------------- TITLE: Celery Crontab Schedule Examples DESCRIPTION: Examples demonstrating various `crontab` expressions for scheduling tasks in Celery, covering minute, hour, day of month, and month of year specifications. Each example shows a `crontab` configuration and its corresponding execution logic. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_8 LANGUAGE: APIDOC CODE: ``` crontab(minute=0, hour='*/5') Execute hour divisible by 5. This means that it is triggered at 3pm, not 5pm (since 3pm equals the 24-hour clock value of "15", which is divisible by 5). ``` LANGUAGE: APIDOC CODE: ``` crontab(minute=0, hour='*/3,8-17') Execute every hour divisible by 3, and every hour during office hours (8am-5pm). ``` LANGUAGE: APIDOC CODE: ``` crontab(0, 0, day_of_month='2') Execute on the second day of every month. ``` LANGUAGE: APIDOC CODE: ``` crontab(0, 0, day_of_month='2-30/2') Execute on every even numbered day. ``` LANGUAGE: APIDOC CODE: ``` crontab(0, 0, day_of_month='1-7,15-21') Execute on the first and third weeks of the month. ``` LANGUAGE: APIDOC CODE: ``` crontab(0, 0, day_of_month='11', month_of_year='5') Execute on the eleventh of May every year. ``` LANGUAGE: APIDOC CODE: ``` crontab(0, 0, month_of_year='*/3') Execute every day on the first month of every quarter. ``` ---------------------------------------- TITLE: Celery Beat Entry Fields Reference DESCRIPTION: This section describes the available configuration fields for a Celery beat schedule entry. These fields define the task to execute, its schedule, and any arguments or execution options. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_5 LANGUAGE: APIDOC CODE: ``` task: Type: string Description: The name of the task to execute. Not the import path. schedule: Type: integer (seconds), datetime.timedelta, celery.schedules.crontab, or custom schedule type Description: The frequency of execution. args: Type: list or tuple Description: Positional arguments for the task. kwargs: Type: dict Description: Keyword arguments for the task. options: Type: dict Description: Execution options, such as 'exchange', 'routing_key', 'expires', supported by Task.apply_async. relative: Type: boolean Description: If true, datetime.timedelta schedules are rounded to the nearest second, minute, hour, or day. Defaults to false, meaning frequency is relative to celery beat start time. ``` ---------------------------------------- TITLE: Customize Periodic Task Schedule at Runtime DESCRIPTION: Demonstrates how to change the interval of a periodic task at runtime by subclassing `celery.schedules.schedule` and overriding its `is_due` method. This allows for dynamic scheduling logic beyond fixed intervals. SOURCE: https://github.com/celery/celery/blob/main/docs/faq.rst#_snippet_17 LANGUAGE: python CODE: ``` from celery.schedules import schedule class my_schedule(schedule): def is_due(self, last_run_at): return run_now, next_time_to_check ``` ---------------------------------------- TITLE: Celery Beat Schedule Filename Setting DESCRIPTION: The `beat_schedule_filename` setting defines the name of the file used by `PersistentScheduler` to store periodic task run times. It defaults to `"celerybeat-schedule"`. The suffix `.db` may be appended. It can also be set via the `celery beat --schedule` argument. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_195 LANGUAGE: APIDOC CODE: ``` beat_schedule_filename: Default: "celerybeat-schedule" Description: Name of the file used by `PersistentScheduler` to store the last run times of periodic tasks. Suffix `.db` may be appended. Can be set via `celery beat --schedule` argument. ``` ---------------------------------------- TITLE: Schedule `starmap` execution asynchronously in Celery DESCRIPTION: Shows how to schedule a `starmap` operation to run after a specified delay using `apply_async` with a `countdown`. This demonstrates that `map` and `starmap` are signature objects. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_75 LANGUAGE: pycon CODE: ``` >>> add.starmap(zip(range(10), range(10))).apply_async(countdown=10) ``` ---------------------------------------- TITLE: Configure Custom Celery Beat Schedule File Location DESCRIPTION: Command to start Celery Beat and specify a custom path for its schedule database file. This is useful when the default celerybeat-schedule file cannot be written to the current directory, allowing for explicit control over its storage location. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_15 LANGUAGE: console CODE: ``` celery -A proj beat -s /home/celery/var/run/celerybeat-schedule ``` ---------------------------------------- TITLE: Configure Celerybeat Scheduler in Python DESCRIPTION: This snippet demonstrates how to set the `CELERYBEAT_SCHEDULER` configuration option in Celery. This setting defines the default scheduler class used by `celerybeat`, allowing users to specify custom or database-backed schedulers. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.1.rst#_snippet_0 LANGUAGE: python CODE: ``` CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' ``` ---------------------------------------- TITLE: Inspect Scheduled Celery Tasks DESCRIPTION: Displays tasks that have been reserved by workers due to an `eta` or `countdown` argument. These tasks are scheduled for future execution. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/monitoring.rst#_snippet_8 LANGUAGE: console CODE: ``` $ celery -A proj inspect scheduled ``` ---------------------------------------- TITLE: Celery Solar Schedule Event Types DESCRIPTION: Defines the various astronomical and civil event types that can be used with Celery's `solar` schedule, such as `dawn_astronomical`, `dawn_nautical`, and `dawn_civil`, along with their precise astronomical definitions. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_11 LANGUAGE: APIDOC CODE: ``` Event Types: dawn_astronomical: Execute at the moment after which the sky is no longer completely dark. This is when the sun is 18 degrees below the horizon. dawn_nautical: Execute when there's enough sunlight for the horizon and some objects to be distinguishable; formally, when the sun is 12 degrees below the horizon. dawn_civil: Execute when there's enough light for ``` ---------------------------------------- TITLE: Schedule Celery Task with `eta` for Precise Future Execution DESCRIPTION: This snippet illustrates how to schedule a Celery task to run at a specific future date and time using the `eta` argument. It requires a `datetime.datetime` object, preferably with timezone information, to define the exact execution time. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/calling.rst#_snippet_13 LANGUAGE: pycon CODE: ``` >>> from datetime import datetime, timedelta, timezone >>> tomorrow = datetime.now(timezone.utc) + timedelta(days=1) >>> add.apply_async((2, 2), eta=tomorrow) ``` ---------------------------------------- TITLE: Celery Task Scheduling with apply_async (Python) DESCRIPTION: Demonstrates how to schedule Celery tasks using `apply_async` with `countdown` for delayed execution and `eta` for execution at a specific future datetime. This method provides advanced control over task scheduling. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_48 LANGUAGE: Python CODE: ``` # Run 10 seconds into the future. res = apply_async(MyTask, countdown=10); # Run 1 day from now res = apply_async(MyTask, eta=datetime.now() + timedelta(days=1)) ``` ---------------------------------------- TITLE: Configure Celery Periodic Tasks via beat_schedule Setting DESCRIPTION: This Python snippet illustrates how to define periodic tasks directly within the `app.conf.beat_schedule` dictionary. This method allows for manual configuration of task names, target tasks, schedules, and arguments. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_4 LANGUAGE: python CODE: ``` app.conf.beat_schedule = { 'add-every-30-seconds': { 'task': 'tasks.add', 'schedule': 30.0, 'args': (16, 16) } } app.conf.timezone = 'UTC' ``` ---------------------------------------- TITLE: Dump Scheduled (ETA) Tasks on Celery Worker (Python) DESCRIPTION: Illustrates how to retrieve tasks waiting to be scheduled with an ETA or countdown using the `i.scheduled()` method. This helps monitor tasks that are set to run at a future time. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/workers.rst#_snippet_33 LANGUAGE: pycon CODE: ``` >>> i.scheduled() [{'worker1.example.com': [{'eta': '2010-06-07 09:07:52', 'priority': 0, 'request': { 'name': 'tasks.sleeptask', 'id': '1a7980ea-8b19-413e-91d2-0b74f3844c4d', 'args': '[1]', 'kwargs': '{}'}}, {'eta': '2010-06-07 09:07:53', 'priority': 0, 'request': { 'name': 'tasks.sleeptask', 'id': '49661b9a-aa22-4120-94b7-9ee8031d219d', 'args': '[2]', 'kwargs': '{}'}}]}] ``` ---------------------------------------- TITLE: Django Celery Beat Database Schema DESCRIPTION: This API documentation outlines the database tables created by `django-celery-beat` when using a database-backed schedule. These tables, including `PeriodicTask`, `IntervalSchedule`, `CrontabSchedule`, and `PeriodicTasks`, are essential for managing and storing periodic task definitions and their schedules. SOURCE: https://github.com/celery/celery/blob/main/docs/faq.rst#_snippet_24 LANGUAGE: APIDOC CODE: ``` django-celery-beat Database Tables: - PeriodicTask: Stores definitions of periodic tasks. - IntervalSchedule: Defines schedules based on time intervals. - CrontabSchedule: Defines schedules based on crontab expressions. - PeriodicTasks: Helper table for managing periodic tasks. ``` ---------------------------------------- TITLE: Celery Solar Schedule Function Arguments DESCRIPTION: Documentation for the `solar(event, latitude, longitude)` function, detailing the meaning of positive and negative signs for latitude and longitude when specifying geographical coordinates. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_10 LANGUAGE: APIDOC CODE: ``` solar(event, latitude, longitude) Arguments: latitude: +: North -: South longitude: +: East -: West ``` ---------------------------------------- TITLE: APIDOC: Celery Remote Control and Beat Scheduler Updates DESCRIPTION: Describes new remote control commands for worker configuration and stats, and an update to the beat scheduler to use a customizable `now()` method for schedules. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-3.0.rst#_snippet_22 LANGUAGE: APIDOC CODE: ``` Stats Broadcast Command: Now includes the workers pid. Conf Remote Control Command: New command to get a worker's current configuration. Chord Unlock Task: Ability to modify the chord unlock task's countdown argument (Issue #1146). Beat Scheduler: Now uses the `now()` method of the schedule, allowing custom date/time provision. ``` ---------------------------------------- TITLE: Start Celery Beat Service DESCRIPTION: Command to start the Celery Beat service, which is responsible for scheduling periodic tasks. It requires specifying the Celery application module. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_13 LANGUAGE: console CODE: ``` celery -A proj beat ``` ---------------------------------------- TITLE: Python: Crontab Expressions for Periodic Tasks DESCRIPTION: These Python console snippets demonstrate how to define crontab expressions for periodic tasks. The first shows a simple 'every 15 minutes' schedule, while the second illustrates a more complex schedule for specific hours and days of the week. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.0.rst#_snippet_22 LANGUAGE: pycon CODE: ``` >>> crontab(minute='*/15') ``` LANGUAGE: pycon CODE: ``` >>> crontab(minute='*/30', hour='8-17,1-2', day_of_week='thu-fri') ``` ---------------------------------------- TITLE: Start Celerybeat Scheduler DESCRIPTION: Command to launch the `celerybeat` daemon, which is responsible for scheduling periodic tasks. It's crucial to run this on only one server to avoid duplicate execution of periodic tasks, as the periodic task system has been centralized. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_33 LANGUAGE: Console CODE: ``` $ celerybeat ``` ---------------------------------------- TITLE: Beat Hanging After First Schedule Iteration Fix DESCRIPTION: Resolves a problem where Celery Beat would hang after its first schedule iteration. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-3.1.rst#_snippet_53 LANGUAGE: APIDOC CODE: ``` Component: Beat Issue: Hanging after first schedule iteration Status: Fixed. ``` ---------------------------------------- TITLE: Import Crontab and Periodic Task for Celery Scheduling DESCRIPTION: Example Python code demonstrating the necessary imports for implementing crontab-like scheduling with Celery's periodic tasks. It imports `crontab` from `celery.schedules` and `periodic_task` from `celery.decorators`. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_2 LANGUAGE: python CODE: ``` from celery.schedules import crontab from celery.decorators import periodic_task ``` ---------------------------------------- TITLE: Timer.call_after Method API DESCRIPTION: Documents the `timer.call_after` method, which schedules a given callback function to be executed after a specified number of seconds, optionally with arguments. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_41 LANGUAGE: APIDOC CODE: ``` timer.call_after(secs, callback, args=(), kwargs=()): secs: Delay in seconds before the callback is executed. callback: The function to call. args: Positional arguments to pass to the callback. kwargs: Keyword arguments to pass to the callback. ``` ---------------------------------------- TITLE: Schedule Celery Task with `countdown` for Delayed Execution DESCRIPTION: This example demonstrates using the `countdown` argument with `apply_async` to delay a task's execution by a specified number of seconds. The `result.get()` call will block until the countdown expires and the task completes. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/calling.rst#_snippet_12 LANGUAGE: pycon CODE: ``` >>> result = add.apply_async((2, 2), countdown=3) >>> result.get() # this takes at least 3 seconds to return 4 ``` ---------------------------------------- TITLE: Update Deprecated Celery Schedule Import DESCRIPTION: Demonstrates how to replace the deprecated `celery.task.schedules` import with the new `celery.schedules` module for `crontab` and other schedule-related functionalities, reflecting a change in module organization. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.2.rst#_snippet_29 LANGUAGE: Python CODE: ``` # Old (deprecated) from celery.task.schedules import crontab # New (recommended) from celery.schedules import crontab ``` ---------------------------------------- TITLE: Schedule Error Handlers for Non-Registered Tasks in Celery DESCRIPTION: This Python code demonstrates how to schedule error handlers that are not registered tasks in the current worker. It uses `celery.Signature` to define a task 'bar' and links an error handler 'msg.err' to it, which will be sent to the 'msg' queue upon failure, allowing for flexible error handling. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-4.3.rst#_snippet_0 LANGUAGE: python CODE: ``` from celery import Signature Signature( 'bar', args=['foo'], link_error=Signature('msg.err', queue='msg') ).apply_async() ``` ---------------------------------------- TITLE: Celery Worker Setting: Timer Precision DESCRIPTION: Sets the maximum time (in seconds) the ETA scheduler can sleep before rechecking the schedule. A lower value increases precision but may consume more resources. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_146 LANGUAGE: APIDOC CODE: ``` Setting: worker_timer_precision Default: 1.0 seconds Description: Set the maximum time in seconds that the ETA scheduler can sleep between rechecking the schedule. If you need near millisecond precision you can set this to 0.1. ``` ---------------------------------------- TITLE: Schedule Unregistered Error Handlers with Celery Signature DESCRIPTION: This Python code demonstrates how to schedule an error handler that is not a registered task within the current worker using Celery's Signature. It shows linking a separate Signature instance, 'msg.err', to the `link_error` parameter of the main task's Signature, allowing for flexible error handling and routing to a specific queue. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-4.4.rst#_snippet_0 LANGUAGE: Python CODE: ``` from celery import Signature Signature( 'bar', args=['foo'], link_error=Signature('msg.err', queue='msg') ).apply_async() ``` ---------------------------------------- TITLE: Celery Beat Solar Event Triggers DESCRIPTION: Defines various solar events that can be used as triggers for scheduled tasks in Celery Beat. Each event specifies a precise moment relative to the sun's position, such as sunrise, sunset, and different stages of twilight. These events are calculated in UTC and are designed to handle polar regions. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_12 LANGUAGE: APIDOC CODE: ``` Event: dawn_astronomical Description: Execute at the moment when the sky begins to lighten; formally, when the Sun is 18 degrees below the horizon. Event: dawn_nautical Description: Execute when the sun is 12 degrees below the horizon. The horizon becomes visible, and objects are distinguishable. Event: dawn_civil Description: Execute at the beginning of civil twilight, when objects to be distinguishable so that outdoor activities can commence; formally, when the Sun is 6 degrees below the horizon. Event: sunrise Description: Execute when the upper edge of the sun appears over the eastern horizon in the morning. Event: solar_noon Description: Execute when the sun is highest above the horizon on that day. Event: sunset Description: Execute when the trailing edge of the sun disappears over the western horizon in the evening. Event: dusk_civil Description: Execute at the end of civil twilight, when objects are still distinguishable and some stars and planets are visible. Formally, when the sun is 6 degrees below the horizon. Event: dusk_nautical Description: Execute when the sun is 12 degrees below the horizon. Objects are no longer distinguishable, and the horizon is no longer visible to the naked eye. Event: dusk_astronomical Description: Execute at the moment after which the sky becomes completely dark; formally, when the sun is 18 degrees below the horizon. ``` ---------------------------------------- TITLE: Define Celery Periodic Tasks using on_after_configure Signal DESCRIPTION: This Python example shows how to define periodic tasks using the `on_after_configure` signal. It demonstrates adding tasks with fixed intervals and cron-like schedules, ensuring tasks are registered after the Celery app is fully set up. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_3 LANGUAGE: python CODE: ``` from celery import Celery from celery.schedules import crontab app = Celery() @app.on_after_configure.connect def setup_periodic_tasks(sender: Celery, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') # Calls test('hello') every 30 seconds. # It uses the same signature of previous task, an explicit name is # defined to avoid this task replacing the previous one defined. sender.add_periodic_task(30.0, test.s('hello'), name='add every 30') # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) # Executes every Monday morning at 7:30 a.m. sender.add_periodic_task( crontab(hour=7, minute=30, day_of_week=1), test.s('Happy Mondays!'), ) @app.task def test(arg): print(arg) @app.task def add(x, y): z = x + y print(z) ``` ---------------------------------------- TITLE: Celery Beat Module API Reference DESCRIPTION: This entry provides a reference to the `celery.beat` module, indicating that its full API, including all public and undocumented members, is documented. The module is central to Celery's periodic task scheduling. SOURCE: https://github.com/celery/celery/blob/main/docs/reference/celery.beat.rst#_snippet_0 LANGUAGE: APIDOC CODE: ``` Module: celery.beat Description: The celery.beat module provides a scheduler that periodically executes Celery tasks. Members: All public members of the celery.beat module. Undocumented Members: All undocumented members of the celery.beat module. ``` ---------------------------------------- TITLE: Celery Beat: beat_max_loop_interval Setting DESCRIPTION: Configures the maximum number of seconds Celery Beat can sleep between checking the schedule. The default value is 0, which is scheduler-specific; for the default Celery scheduler, it's 300 seconds (5 minutes), while for django-celery-beat, it's 5 seconds. When running embedded on Jython, it's overridden to 1 second for timely shutdown. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_197 LANGUAGE: APIDOC CODE: ``` Setting: beat_max_loop_interval Default: 0 (scheduler specific, e.g., 300s for default Celery, 5s for django-celery-beat) Description: The maximum number of seconds celery.bin.beat can sleep between checking the schedule. Note: Overridden to 1s on Jython when embedded for timely shutdown. ``` ---------------------------------------- TITLE: Improvement: celerybeat PersistentScheduler handles corrupted files DESCRIPTION: The `PersistentScheduler` in `celerybeat` now includes logic to automatically remove corrupted schedule files, enhancing robustness (Issue #346). SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.2.rst#_snippet_12 LANGUAGE: APIDOC CODE: ``` celerybeat: PersistentScheduler Behavior: Automatically removes corrupted schedule files (Issue #346). ``` ---------------------------------------- TITLE: Celery Beat: beat_cron_starting_deadline Setting DESCRIPTION: Specifies the number of seconds Celery Beat can look back when determining if a cron schedule is due. If set to None, cron jobs that are past due will always run immediately. Setting this value higher than 3600 seconds (1 hour) is strongly discouraged. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_198 LANGUAGE: APIDOC CODE: ``` Setting: beat_cron_starting_deadline Version Added: 5.3 Default: None Description: When using cron, the number of seconds celery.bin.beat can look back when deciding whether a cron schedule is due. Note: If set to None, past due cronjobs always run immediately. Setting higher than 3600s (1 hour) is highly discouraged. ``` ---------------------------------------- TITLE: Celery Setting: beat_cron_starting_deadline DESCRIPTION: API documentation for the `beat_cron_starting_deadline` setting. This setting controls how far back `celery beat` can look when determining if a cron schedule is due. Setting it to `None` ensures past due cronjobs run immediately. SOURCE: https://github.com/celery/celery/blob/main/docs/history/whatsnew-5.3.rst#_snippet_4 LANGUAGE: APIDOC CODE: ``` Setting: beat_cron_starting_deadline Type: int or None Description: Number of seconds `celery beat` can look back for cron schedules. Behavior: If None, past due cronjobs run immediately. ``` ---------------------------------------- TITLE: Celery Signal Handling: SIGTERM and SIGINT DESCRIPTION: Documents that `celerybeat` now gracefully handles `SIGTERM` and `SIGINT` signals by syncing the schedule to disk. This ensures that the schedule is persisted during shutdown, preventing data loss. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_26 LANGUAGE: APIDOC CODE: ``` SIGTERM Description: Signal for graceful termination. Handled by celerybeat to sync schedule to disk. SIGINT Description: Signal for interrupt. Handled by celerybeat to sync schedule to disk. ``` ---------------------------------------- TITLE: Embedded Beat App Context Fix DESCRIPTION: Ensures that the embedded beat scheduler properly sets the application context for its threads and processes, preventing potential context-related issues. (Issue #2594). SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-3.1.rst#_snippet_5 LANGUAGE: APIDOC CODE: ``` Component: Worker (Embedded Beat) Issue: #2594 Description: Embedded beat now properly sets app for thread/process. ``` ---------------------------------------- TITLE: Celery Timer Module API Reference DESCRIPTION: Detailed API documentation for the `timer` module in Celery, outlining methods for scheduling callbacks based on time delays, repetitions, or specific timestamps. These methods are fundamental for managing asynchronous task execution within the Celery ecosystem. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_42 LANGUAGE: APIDOC CODE: ``` Module: timer Method: call_after Signature: timer.call_after(secs, callback, args=(), kwargs=(), priority=0) Description: Schedules a callback to be executed once after a specified number of seconds. Parameters: secs (int/float): The delay in seconds before the callback is executed. callback (callable): The function or callable to execute. args (tuple, optional): Positional arguments to pass to the callback. Defaults to an empty tuple. kwargs (dict, optional): Keyword arguments to pass to the callback. Defaults to an empty dictionary. priority (int, optional): The priority level for the scheduled task. Defaults to 0. Method: call_repeatedly Signature: timer.call_repeatedly(secs, callback, args=(), kwargs=(), priority=0) Description: Schedules a callback to be executed repeatedly at a specified interval. Parameters: secs (int/float): The interval in seconds between each execution of the callback. callback (callable): The function or callable to execute. args (tuple, optional): Positional arguments to pass to the callback. Defaults to an empty tuple. kwargs (dict, optional): Keyword arguments to pass to the callback. Defaults to an empty dictionary. priority (int, optional): The priority level for the scheduled task. Defaults to 0. Method: call_at Signature: timer.call_at(eta, callback, args=(), kwargs=(), priority=0) Description: Schedules a callback to be executed at a specific future time. Parameters: eta (datetime): The exact time (datetime object) when the callback should be executed. callback (callable): The function or callable to execute. args (tuple, optional): Positional arguments to pass to the callback. Defaults to an empty tuple. kwargs (dict, optional): Keyword arguments to pass to the callback. Defaults to an empty dictionary. priority (int, optional): The priority level for the scheduled task. Defaults to 0. ``` ---------------------------------------- TITLE: `celerybeat` Reuses Connection for Large Task Sets DESCRIPTION: The `celerybeat` scheduler now reuses the same connection when publishing large sets of tasks. This optimization improves performance and reduces overhead by minimizing connection establishment. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_7 LANGUAGE: APIDOC CODE: ``` ``celerybeat``: Now reuses the same connection when publishing large sets of tasks. ``` ---------------------------------------- TITLE: Schedule Celery Task After Django Transaction Commit DESCRIPTION: This Python snippet demonstrates how to use Django's `transaction.on_commit` to defer the execution of a Celery task until after a database transaction has been successfully committed. This pattern ensures that tasks related to model changes are only processed if the transaction is not rolled back, maintaining data integrity. It shows an example of creating an article and then scheduling a notification task. SOURCE: https://github.com/celery/celery/blob/main/docs/history/whatsnew-4.0.rst#_snippet_0 LANGUAGE: Python CODE: ``` from functools import partial from django.db import transaction from .models import Article, Log from .tasks import send_article_created_notification def create_article(request): with transaction.atomic(): article = Article.objects.create(**request.POST) # send this task only if the rest of the transaction succeeds. transaction.on_commit(partial( ``` ---------------------------------------- TITLE: Celery Task Expiration with apply_async DESCRIPTION: This snippet demonstrates how to schedule a Celery task (`add`) to expire after a specified duration using `apply_async`. The `expires` argument sets the task's expiration time, after which it will be marked as REVOKED if not processed. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/calling.rst#_snippet_17 LANGUAGE: pycon CODE: ``` add.apply_async((10, 10), kwargs, expires=datetime.now(timezone.utc) + timedelta(days=1)) ``` ---------------------------------------- TITLE: Create Celery Chain with Pipe Operator DESCRIPTION: Demonstrates an alternative, more concise syntax for creating a Celery task chain using the `|` (pipe) operator. The `apply_async()` method schedules the chain for asynchronous execution. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_44 LANGUAGE: pycon CODE: ``` >>> (add.s(2, 2) | mul.s(8) | mul.s(10)).apply_async() ``` ---------------------------------------- TITLE: Celery Worker Prefork Pool Configuration Options DESCRIPTION: Documents command-line options and settings for configuring the Celery worker's prefork pool behavior, including scheduling strategy and memory limits. It explains the `-Ofair` and `-Ofast` options for task scheduling and the `--max-memory-per-child` option/setting for memory management. SOURCE: https://github.com/celery/celery/blob/main/docs/history/whatsnew-4.0.rst#_snippet_20 LANGUAGE: APIDOC CODE: ``` Command-line Option: -Ofair Description: Default scheduling strategy for prefork pool. Ensures no task is sent to a child process already executing a task. Note: May perform slightly worse for only short-running tasks. Command-line Option: -Ofast Description: Re-enables the default scheduling behavior from Celery 3.1 (tasks sent to first writable inqueue, round-robin). Command-line Option: --max-memory-per-child <kilobytes> Description: Limits the maximum amount of resident memory (RSS) allocated per prefork pool child process. Unit: Kilobytes. Behavior: A child process exceeding the limit is terminated and replaced after its current task completes. Setting: worker_max_memory_per_child Description: Configuration setting equivalent to --max-memory-per-child. Log File Format Option: %I Description: Used in init-scripts and 'celery multi' to ensure each child process has a separate log file (e.g., /var/log/celery/%n%I.log). Program: celery multi ``` ---------------------------------------- TITLE: Execute Celery Task Signature with .apply_async() DESCRIPTION: Shows how to use `apply_async` with a task signature, providing arguments, keyword arguments, and execution options. This method offers fine-grained control over task execution, including scheduling and routing. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_7 LANGUAGE: python CODE: ``` add.apply_async(args, kwargs, **options) add.signature(args, kwargs, **options).apply_async() add.apply_async((2, 2), countdown=1) add.signature((2, 2), countdown=1).apply_async() ``` ---------------------------------------- TITLE: Reset Django-Celery-Beat Periodic Tasks (Modern) DESCRIPTION: For Celery 4.0 and above, using `django-celery-beat`, this console command resets the `last_run_at` field for `PeriodicTask` objects. This is crucial when timezone settings change and the scheduler doesn't automatically reset. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_2 LANGUAGE: console CODE: ``` $ python manage.py shell >>> from django_celery_beat.models import PeriodicTask >>> PeriodicTask.objects.update(last_run_at=None) ``` ---------------------------------------- TITLE: Define Worker Bootstep Requiring Timer Component DESCRIPTION: Example of a Celery worker bootstep that requires the `Timer` component. This allows the bootstep to schedule functions using the worker's timer. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_6 LANGUAGE: python CODE: ``` class WorkerStep(bootsteps.StartStopStep): requires = {'celery.worker.components:Timer'} ``` ---------------------------------------- TITLE: Celery Beat: `celery.beat.Scheduler.schedules_equal` Handles `None` Arguments DESCRIPTION: The `schedules_equal` method within `celery.beat.Scheduler` has been updated to gracefully handle cases where one or both of its input arguments are `None`. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-4.3.rst#_snippet_8 LANGUAGE: APIDOC CODE: ``` Method Behavior Update: Method: celery.beat.Scheduler.schedules_equal Signature: schedules_equal(self, schedule1, schedule2) New Behavior: Accepts `None` for `schedule1` or `schedule2`. ``` ---------------------------------------- TITLE: Implement Deadlock Detection Bootstep Using Worker Timer DESCRIPTION: An example bootstep that uses the worker's timer to periodically check for deadlocked requests. It requires the `Timer` component and demonstrates `call_repeatedly` for scheduled tasks and proper cleanup in `stop`. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_11 LANGUAGE: python CODE: ``` from celery import bootsteps class DeadlockDetection(bootsteps.StartStopStep): requires = {'celery.worker.components:Timer'} def __init__(self, worker, deadlock_timeout=3600): self.timeout = deadlock_timeout self.requests = [] self.tref = None def start(self, worker): # run every 30 seconds. self.tref = worker.timer.call_repeatedly( 30.0, self.detect, (worker,), priority=10, ) def stop(self, worker): if self.tref: self.tref.cancel() self.tref = None def detect(self, worker): # update active requests for req in worker.active_requests: if req.time_start and time() - req.time_start > self.timeout: raise SystemExit() ``` ---------------------------------------- TITLE: Celery Worker Timer Setting DESCRIPTION: The `worker_timer` setting defines the name of the ETA scheduler class used by the worker. It defaults to `"kombu.asynchronous.hub.timer:Timer"` or is set by the pool implementation. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_186 LANGUAGE: APIDOC CODE: ``` worker_timer: Default: "kombu.asynchronous.hub.timer:Timer" Description: Name of the ETA scheduler class used by the worker. Default is or set by the pool implementation. ``` ---------------------------------------- TITLE: Reset Django-Celery Periodic Tasks (Legacy) DESCRIPTION: For older Django-Celery versions (4.0 and below), this console command resets the `last_run_at` field for `PeriodicTask` objects. This is necessary when timezone settings change and the scheduler doesn't automatically reset. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_1 LANGUAGE: console CODE: ``` $ python manage.py shell >>> from djcelery.models import PeriodicTask >>> PeriodicTask.objects.update(last_run_at=None) ``` ---------------------------------------- TITLE: Celery Signal: beat_init DESCRIPTION: The `beat_init` signal is dispatched whenever the `celerybeat` scheduler starts, regardless of whether it's running as a standalone process or embedded within another application. The sender of this signal is always an instance of `celery.beat.Service`. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-2.2.rst#_snippet_41 LANGUAGE: APIDOC CODE: ``` celery.signals.beat_init: Description: Dispatched when celerybeat starts (standalone or embedded). Sender: celery.beat.Service instance. ``` ---------------------------------------- TITLE: Celery Consumer Methods API DESCRIPTION: This section documents key methods available on the Celery consumer object, including functionalities for resetting rate limits, creating task buckets, and managing task queues for consumption. It also covers scheduling ETA tasks. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/extending.rst#_snippet_24 LANGUAGE: APIDOC CODE: ``` consumer.reset_rate_limits() Updates the ``task_buckets`` mapping for all registered task types. consumer.bucket_for_task(type, Bucket=TokenBucket) Creates rate limit bucket for a task using its ``task.rate_limit`` attribute. consumer.add_task_queue(name, exchange=None, exchange_type=None, routing_key=None, \*\*options): Adds new queue to consume from. This will persist on connection restart. consumer.cancel_task_queue(name) Stop consuming from queue by name. This will persist on connection restart. apply_eta_task(request) Schedule ETA task to execute based on the ``request.eta`` attribute. (:class:`~celery.worker.request.Request`) ``` ---------------------------------------- TITLE: APIDOC: Timezone Information in `eta` and `expires` DESCRIPTION: This change indicates that the task message `eta` and `expires` fields now include timezone information. This enhancement ensures more accurate and reliable scheduling and expiry handling across different timezones. SOURCE: https://github.com/celery/celery/blob/main/docs/history/whatsnew-3.1.rst#_snippet_46 LANGUAGE: APIDOC CODE: ``` Task Fields: eta, expires Description: Now include timezone information. ``` ---------------------------------------- TITLE: Embed Celerybeat in Celeryd Worker DESCRIPTION: Command to embed the `celerybeat` scheduler directly within the `celeryd` worker process. This is useful for setups with only a single worker server, eliminating the need to run `celerybeat` as a separate daemon. SOURCE: https://github.com/celery/celery/blob/main/docs/history/changelog-1.0.rst#_snippet_34 LANGUAGE: Console CODE: ``` $ celeryd --beat # Embed celerybeat in celeryd. ``` ---------------------------------------- TITLE: Start Celery beat service with Django DatabaseScheduler DESCRIPTION: Launches the Celery beat service, specifying the DatabaseScheduler from django-celery-beat to manage and execute periodic tasks defined in the Django database. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_19 LANGUAGE: Shell CODE: ``` $ celery -A proj beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler ``` ---------------------------------------- TITLE: Configure Celery Beat Timezone in Python DESCRIPTION: This snippet demonstrates how to set the timezone for Celery Beat using the `timezone` setting. This can be done directly on the app configuration or via a configuration module. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/periodic-tasks.rst#_snippet_0 LANGUAGE: python CODE: ``` timezone = 'Europe/London' ``` ---------------------------------------- TITLE: Configure Event Queue Message TTL DESCRIPTION: Sets the message expiry time for messages sent to a monitor client's event queue. Messages are deleted after this duration. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_154 LANGUAGE: APIDOC CODE: ``` Setting: event_queue_ttl Transports Supported: amqp Default: 5.0 seconds Description: Message expiry time in seconds (int/float) for when messages sent to a monitor clients event queue is deleted (x-message-ttl). For example, if this value is set to 10 then a message delivered to this queue will be deleted after 10 seconds. ``` ---------------------------------------- TITLE: Celery Task Request Object Attributes DESCRIPTION: Documents the various attributes available on the `self.request` object within a Celery task, providing metadata about the task's execution environment, scheduling, and message delivery. These attributes offer insights into how the task was invoked and its current state. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/tasks.rst#_snippet_15 LANGUAGE: APIDOC CODE: ``` Task Request Attributes: is_eager: bool - Set to True if the task is executed locally in the client, not by a worker. eta: datetime.datetime (UTC) - The original ETA of the task (if any). This is in UTC time (depending on the enable_utc setting). expires: datetime.datetime (UTC) - The original expiry time of the task (if any). This is in UTC time (depending on the enable_utc setting). hostname: str - Node name of the worker instance executing the task. delivery_info: dict - Additional message delivery information. This is a mapping containing the exchange and routing key used to deliver this task. Used by for example Task.retry() to resend the task to the same destination queue. Availability of keys in this dict depends on the message broker used. reply-to: str - Name of queue to send replies back to (used with RPC result backend for example). called_directly: bool - This flag is set to true if the task wasn't executed by the worker. timelimit: tuple[soft_limit: int | None, hard_limit: int | None] - A tuple of the current (soft, hard) time limits active for this task (if any). callbacks: list[Signature] - A list of signatures to be called if this task returns successfully. errbacks: list[Signature] - A list of signatures to be called if this task fails. utc: bool - Set to true the caller has UTC enabled (enable_utc setting). headers: dict | None - Mapping of message headers sent with this task message (may be None). (versionadded 3.1) reply_to: str - Where to send reply to (queue name). (versionadded 3.1) correlation_id: str - Usually the same as the task id, often used in AMQP to keep track of what a reply is for. (versionadded 3.1) root_id: str | None - The unique id of the first task in the workflow this task is part of (if any). (versionadded 4.0) parent_id: str | None - The unique id of the task that called this task (if any). (versionadded 4.0) chain: list[Task] - Reversed list of tasks that form a chain (if any). The last item in this list will be the next task to succeed the current task. If using version one of the task protocol the chain tasks will be in request.callbacks instead. (versionadded 4.0) properties: dict | None - Mapping of message properties received with this task message (may be None or {}). (versionadded 5.2) replaced_task_nesting: int - How many times the task was replaced, if at all (may be 0). (versionadded 5.2) ``` ---------------------------------------- TITLE: Celery Beat Sync Every Setting DESCRIPTION: The `beat_sync_every` setting determines the number of periodic tasks that can be called before another database sync is issued. It defaults to `0`. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_196 LANGUAGE: APIDOC CODE: ``` beat_sync_every: Default: 0 Description: The number of periodic tasks that can be called before another database sync is issued. ``` ---------------------------------------- TITLE: Configure GCS Result Backend Time-To-Live (TTL) DESCRIPTION: Sets the time-to-live for results stored in Google Cloud Storage, enabling automatic deletion after a specified duration. Requires a GCS bucket with 'Delete' Object Lifecycle Management action enabled. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/configuration.rst#_snippet_76 LANGUAGE: Python CODE: ``` gcs_ttl = 86400 ``` ---------------------------------------- TITLE: Skew countdown for tasks within a Celery group DESCRIPTION: Shows how to apply a `skew` to a group, setting a progressively increasing `countdown` for each task within the group. This can be used to stagger task execution over time. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_80 LANGUAGE: pycon CODE: ``` >>> group.skew(start=1, stop=10)() ``` ---------------------------------------- TITLE: Using the `~` prefix operator for task signatures DESCRIPTION: Demonstrates a shortcut for task signatures in the Python shell, equivalent to `sig.delay().get()`. This operator is generally not recommended for production code but is handy for experimentation. SOURCE: https://github.com/celery/celery/blob/main/docs/userguide/canvas.rst#_snippet_17 LANGUAGE: pycon CODE: ``` >>> ~sig >>> # is the same as >>> sig.delay().get() ``` ---------------------------------------- TITLE: Configure Celery Application Timezone DESCRIPTION: Sets the specific timezone for the Celery application. While all internal times and messages use UTC, this configuration ensures correct conversion to local time when workers process messages with time-sensitive parameters. SOURCE: https://github.com/celery/celery/blob/main/docs/getting-started/next-steps.rst#_snippet_57 LANGUAGE: python CODE: ``` app.conf.timezone = 'Europe/London' ``` |