{"id":27634754,"url":"https://github.com/farahats9/sqlalchemy-celery-beat","last_synced_at":"2025-04-23T19:24:40.145Z","repository":{"id":159343755,"uuid":"573398508","full_name":"farahats9/sqlalchemy-celery-beat","owner":"farahats9","description":"Celery Periodic Tasks backed by the SQLAlchemy","archived":false,"fork":false,"pushed_at":"2025-04-20T14:29:50.000Z","size":258,"stargazers_count":57,"open_issues_count":4,"forks_count":13,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-23T19:24:03.304Z","etag":null,"topics":["celery","celerybeat","fastapi","flask","periodic-tasks","python","sqlalchemy"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"AngelLiang/celery-sqlalchemy-scheduler","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/farahats9.png","metadata":{"files":{"readme":"README.md","changelog":"changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-12-02T11:20:01.000Z","updated_at":"2025-04-20T14:29:54.000Z","dependencies_parsed_at":"2024-02-14T20:32:25.447Z","dependency_job_id":"4965c5d2-489b-44e4-bd4e-738b8511da4b","html_url":"https://github.com/farahats9/sqlalchemy-celery-beat","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/farahats9%2Fsqlalchemy-celery-beat","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/farahats9%2Fsqlalchemy-celery-beat/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/farahats9%2Fsqlalchemy-celery-beat/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/farahats9%2Fsqlalchemy-celery-beat/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/farahats9","download_url":"https://codeload.github.com/farahats9/sqlalchemy-celery-beat/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250498092,"owners_count":21440416,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["celery","celerybeat","fastapi","flask","periodic-tasks","python","sqlalchemy"],"created_at":"2025-04-23T19:24:39.631Z","updated_at":"2025-04-23T19:24:40.138Z","avatar_url":"https://github.com/farahats9.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# sqlalchemy-celery-beat\n\nA Scheduler Based Sqlalchemy for Celery.\n\n\u003e NOTE: This project was originally developed by [AngelLiang](https://github.com/AngelLiang/celery-sqlalchemy-scheduler) to use sqlalchemy as the database scheduler for Flask or FastAPI, like [django-celery-beat](https://github.com/celery/django-celery-beat) for django. I am trying to continue on his work and maintain a working solution.\n\n### Prerequisites\n\n- Python 3\n- celery \u003e= 5.0\n- sqlalchemy \u003e= 1.4\n\nFirst you must install `celery` and `sqlalchemy`, and `celery` should be \u003e=5.0\n\n```\n$ pip install sqlalchemy celery\n```\n\n### Installing\n\nInstall from PyPi:\n\n```\n$ pip install sqlalchemy-celery-beat\n```\n\nInstall from source by cloning this repository:\n\n```\n$ git clone git@github.com:farahats9/sqlalchemy-celery-beat.git\n$ cd sqlalchemy-celery-beat\n$ python setup.py install\n```\n\n## Usage\n\nAfter you have installed `sqlalchemy_celery_beat`, you can easily start with following steps:\n\nThis is a demo for exmaple, you can check the code in `examples` directory\n\n1. start celery worker\n\n   ```\n   $ celery -A tasks worker -l info\n   ```\n\n2. start the celery beat with `DatabaseScheduler` as scheduler:\n\n   ```\n   $ celery -A tasks beat -S sqlalchemy_celery_beat.schedulers:DatabaseScheduler -l info\n   ```\n\n   you can also use the shorthand argument `-S sqlalchemy`\n\n## Description\n\nAfter the celery beat is started, by default it create a sqlite database(`schedule.db`) in current folder. You can use `SQLiteStudio.exe` to inspect it.\n\nSample from the `PeriodicTask` model's table\n\n![sqlite](screenshot/sqlite.png)\n\nWhen you want to update scheduler, you can update the data in `schedule.db`. But `sqlalchemy_celery_beat` don't update the scheduler immediately. Then you shoule be change the first column's `last_update` field in the `celery_periodic_task_changed` to now datetime. Finally the celery beat will update scheduler at next wake-up time.\n\n### Database Configuration\n\nYou can configure sqlalchemy db uri when you configure the celery, example as:\n\n```Python\nfrom celery import Celery\n\ncelery = Celery('tasks')\n\nbeat_dburi = 'sqlite:///schedule.db'\n\ncelery.conf.update(\n    {\n        'beat_dburi': beat_dburi,\n        'beat_schema': None  # you can make the scheduler tables under different schema (tested for postgresql, not available in sqlite)\n    }\n)\n```\n\nAlso, you can use MySQL or PostgreSQL.\n\n```Python\n# MySQL: `pip install mysql-connector`\nbeat_dburi = 'mysql+mysqlconnector://root:root@127.0.0.1:3306/celery-schedule'\n\n# PostgreSQL: `pip install psycopg2`\nbeat_dburi = 'postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/celery-schedule'\n```\n\n## Passing arguments to SQLAlchemy engine creation\n\nYou can pass arguments using the `beat_engine_options` keyword in the config dictionary, for example let's make the engine use `echo=True` to show verbose ouptut:\n\n```python\ncelery.conf.update(\n    {\n        'beat_dburi': beat_dburi,\n        'beat_engine_options': {\n            'echo': True\n        },\n        ...\n    }\n)\n```\n\nYou can use this to pass any options required by your DB driver, for more information about what options you can use check the SQLAlchemy docs.\n\n## Example Code 1\n\nView `examples/base/tasks.py` for details.\n\nRun Worker in console 1\n\n    $ cd examples/base\n\n    # Celery \u003c 5.0\n    $ celery worker -A tasks:celery -l info\n\n    # Celery \u003e= 5.0\n    $ celery -A tasks:celery worker -l info\n\nRun Beat in console 2\n\n    $ cd examples/base\n\n    # Celery \u003c 5.0\n    $ celery beat -A tasks:celery -S tasks:DatabaseScheduler -l info\n\n    # Celery \u003e= 5.0\n    $ celery -A tasks:celery beat -S tasks:DatabaseScheduler -l info\n\n## Example Code 2\n\n### Example creating interval-based periodic task\n\nTo create a periodic task executing at an interval you must first\ncreate the interval object:\n\n```python\n\u003e\u003e\u003e from sqlalchemy_celery_beat.models import PeriodicTask, IntervalSchedule, Period\n\u003e\u003e\u003e from sqlalchemy_celery_beat.session import SessionManager\n\u003e\u003e\u003e from celeryconfig import beat_dburi\n\u003e\u003e\u003e session_manager = SessionManager()\n\u003e\u003e\u003e session = session_manager.session_factory(beat_dburi)\n\n# executes every 10 seconds.\n\u003e\u003e\u003e schedule = session.query(IntervalSchedule).filter_by(every=10, period=Period.SECONDS).first()\n\u003e\u003e\u003e if not schedule:\n...     schedule = IntervalSchedule(every=10, period=Period.SECONDS)\n...     session.add(schedule)\n...     session.commit()\n```\n\nThat's all the fields you need: a period type and the frequency.\n\nYou can choose between a specific set of periods:\n\n- `Period.DAYS`\n- `Period.HOURS`\n- `Period.MINUTES`\n- `Period.SECONDS`\n- `Period.MICROSECONDS`\n\n_note_:\n\n    If you have multiple periodic tasks executing every 10 seconds,\n    then they should all point to the same schedule object.\n\nNow that we have defined the schedule object, we can create the periodic task\nentry:\n\n```python\n    \u003e\u003e\u003e task = PeriodicTask(\n    ...     schedule_model=schedule,            # we created this above.\n    ...     name='Importing contacts',          # simply describes this periodic task.\n    ...     task='proj.tasks.import_contacts',  # name of task.\n    ... )\n    \u003e\u003e\u003e session.add(task)\n    \u003e\u003e\u003e session.commit()\n```\n\nNote that this is a very basic example, you can also specify the\narguments and keyword arguments used to execute the task, the `queue` to\nsend it to[\\*], and set an expiry time.\n\nHere\\'s an example specifying the arguments, note how JSON serialization\nis required:\n\n    \u003e\u003e\u003e import json\n    \u003e\u003e\u003e from datetime import datetime, timedelta, timezone\n\n    \u003e\u003e\u003e periodic_task = PeriodicTask(\n    ...     schedule_model=schedule,                  # we created this above.\n    ...     name='Importing contacts',          # simply describes this periodic task.\n    ...     task='proj.tasks.import_contacts',  # name of task.\n    ...     args=json.dumps(['arg1', 'arg2']),\n    ...     kwargs=json.dumps({\n    ...        'be_careful': True,\n    ...     }),\n    ...     expires=datetime.now(tz=timezone.utc) + timedelta(seconds=30)\n    ... )\n    ... session.add(periodic_task)\n    ... session.commit()\n\n### Example creating crontab-based periodic task\n\nA crontab schedule has the fields: `minute`, `hour`, `day_of_week`,\n`day_of_month` and `month_of_year`, so if you want the equivalent of a\n`30 * * * *` (execute every 30 minutes) crontab entry you specify:\n\n    \u003e\u003e\u003e from sqlalchemy_celery_beat.models import PeriodicTask, CrontabSchedule\n    \u003e\u003e\u003e schedule = CrontabSchedule(\n    ...     minute='30',\n    ...     hour='*',\n    ...     day_of_week='*',\n    ...     day_of_month='*',\n    ...     month_of_year='*',\n    ...     timezone='UTC',\n    ... )\n\nThe crontab schedule is linked to a specific timezone using the\n'timezone' input parameter.\n\nThen to create a periodic task using this schedule, use the same\napproach as the interval-based periodic task earlier in this document,\nthe `schedule_model` is a generic foreign-key implementation which makes things very easy and efficient:\n\n    \u003e\u003e\u003e periodic_task = PeriodicTask(\n    ...     schedule_model=schedule,\n    ...     name='Importing contacts',\n    ...     task='proj.tasks.import_contacts',\n    ... )\n\nWhat the previous code actually do is this:\n\n    \u003e\u003e\u003e periodic_task = PeriodicTask(\n    ...     schedule_id=schedule.id,\n    ...     discriminator=schedule.discriminator,\n    ...     name='Importing contacts',\n    ...     task='proj.tasks.import_contacts',\n    ... )\n\nSo when you can use `discriminator` + `schedule_id` or use the convenient property `schedule_model` and it will populate them for you behind the scenes.\n\n### Temporarily disable a periodic task\n\nYou can use the `enabled` flag to temporarily disable a periodic task:\n\n    \u003e\u003e\u003e periodic_task.enabled = False\n    \u003e\u003e\u003e session.add(periodic_task)\n    \u003e\u003e\u003e session.commit()\n\nIf you are using a bulk operation to update or delete multiple tasks at the same time, the changes won't be noticed by the scheduler until you do `PeriodicTaskChanged.update_changed()` or `.update_from_session()`\n\nexample:\n\n```python\nfrom sqlalchemy_celery_beat.models import PeriodicTaskChanged\nfrom sqlalchemy_celery_beat.session import SessionManager, session_cleanup\n\nsession_manager = SessionManager()\nsession = session_manager.session_factory(beat_dburi)\n\nwith session_cleanup(session):\n    stmt = update(PeriodicTask).where(PeriodicTask.name == 'task-123').values(enabled=False)\n\n    session.execute(stmt)  # using execute causes no orm event to fire, changes are in the database but the schduler has no idea\n    session.commit()\n\n    PeriodicTaskChanged.update_from_session(session)\n    # now scheduler reloads the tasks and all is good\n```\n\nThis is not needed when you are updating a specific object using `session.add(task)` because it will trigger the `after_update`, `after_delete` or `after_insert` events.\n\n### Example running periodic tasks\n\nThe periodic tasks still need 'workers' to execute them. So make sure\nthe default **Celery** package is installed. (If not installed, please\nfollow the installation instructions here:\n\u003chttps://github.com/celery/celery\u003e)\n\nBoth the worker and beat services need to be running at the same time.\n\n1.  Start a Celery worker service (specify your project name):\n\n        $ celery -A [project-name] worker --loglevel=info\n\n2.  As a separate process, start the beat service (specify the\n    scheduler):\n\n        $ celery -A [project-name] beat -l info --scheduler sqlalchemy_celery_beat.schedulers:DatabaseScheduler\n\n## Working on adding the following features\n\n- ✅ Add `ClockedSchedule` model\n- ✅ Implement a generic foreign key\n- ✅ More robust attribute validation on models\n- ✅ Add Tests\n- Add more examples\n- Support for Async drivers like asyncpg and psycopg3 async mode\n- Use Alembic migrations\n\nAny help with the tasks above or feedback is appreciated 🙂\n\n## Acknowledgments\n\n- [django-celery-beat](https://github.com/celery/django-celery-beat)\n- [celerybeatredis](https://github.com/liuliqiang/celerybeatredis)\n- [celery](https://github.com/celery/celery)\n- [SQLAlchemy](https://www.sqlalchemy.org)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffarahats9%2Fsqlalchemy-celery-beat","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffarahats9%2Fsqlalchemy-celery-beat","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffarahats9%2Fsqlalchemy-celery-beat/lists"}