Cron style scheduler for asynchronous tasks in Django.
- setup recurring tasks via crontab syntax
- lightweight helpers build on top of APScheduler
- Sentry cron monitor support
You need to have Django's Task framework setup properly.
python3 -m pip install django-crontask
# or
python3 -m pip install django-crontask[sentry] # with sentry cron monitor supportAdd crontask to your INSTALLED_APPS in settings.py:
# settings.py
INSTALLED_APPS = [
"crontask",
# ...
]Finally, you launch the scheduler in a separate process:
python3 manage.py crontaskIf you use Redis as a broker, you can use Redis as a lock backend as well. The lock backend is used to prevent multiple instances of the scheduler from running at the same time. This is important if you have multiple instances of your application running.
# settings.py
CRONTASK = {
"REDIS_URL": "redis://localhost:6379/0",
}# tasks.py
from django.tasks import task
from crontask import cron
@cron("*/5 * * * *") # every 5 minutes
@task
def my_task():
my_task.logger.info("Hello World")You can also use other trigger types from APScheduler.
Just import the trigger and use it in the cron decorator.
from django.tasks import task
from django.utils import timezone
from apscheduler.triggers.interval import IntervalTrigger
from crontask import cron
every_ten_minutes = IntervalTrigger(
minutes=10, timezone=timezone.get_default_timezone()
)
@cron(every_ten_minutes)
@task
def my_interval_task():
my_interval_task.logger.info("Hello from interval task")If you use Sentry you can add cron monitors to your tasks.
The monitor's slug will be the actor's name. Like my_task in the example above.
$ python3 manage.py crontask --help
usage: manage.py crontask [-h] [--no-task-loading] [--no-heartbeat] [--version] [-v {0,1,2,3}]
[--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
[--force-color] [--skip-checks]
Run task scheduler for all tasks with the `cron` decorator.
options:
-h, --help show this help message and exit
--no-task-loading Don't load tasks from installed apps.
--no-heartbeat Don't start the heartbeat actor.