16

I'd like to use django_rq and rq-scheduler for offline tasks, but I'm unsure of where to call rq-scheduler's ability to schedule repeating tasks. Right now, I've added my scheduling to a tasks.py module in my app, and import that in __init__.py. There has to be a better way to do this, though, right?

Thanks in advance.

1
  • I think - nowhere. Every time you restart application server, jobs will be added to scheduler queue (tasks will be multiplied on each startup). As workaround you can clear/remove rq:scheduler:scheduled_jobs key on each startup, just before adding them. But remember to avoid adding/removing jobs in worker processes - I have no idea how to achieve that.
    – marcinn
    Sep 3, 2013 at 13:00

4 Answers 4

14

I created a custom management command which modifies and replaces the rqscheduler command included in django_rq. An example is provided here: https://github.com/rq/rq-scheduler/issues/51#issuecomment-362352497

2
  • 2
    IMO this should be the accepted answer. This elegantly solves the problem. In case you aren't seeing what Pete has done, he has subclassed the built in rqscheduler management command to also call the scheduler.schedule command. I was having problems with the schedule method running more than once, and this fixes that. Thanks @Pete!
    – dvcolgan
    Sep 30, 2019 at 16:35
  • This is a great solution. Starts the scheduler process and schedules periodic tasks.
    – madmanick
    Oct 9, 2020 at 0:53
13

The best place I've found to run it is from your AppConfig in apps.py.

def ready(self):
    scheduler = django_rq.get_scheduler('default')

    # Delete any existing jobs in the scheduler when the app starts up
    for job in scheduler.get_jobs():
        job.delete()

    # Have 'mytask' run every 5 minutes
    scheduler.schedule(datetime.utcnow(), 'mytask', interval=60*5)
6
  • 1
    How django rq will detect this scheduler? is it needed to initiate it from somewhere code by calling function? or if not how can i initiate it automatically on running python manage.py rqscheduler? Jan 25, 2016 at 19:53
  • In newer versions of Django you can create an apps.py file that used to configure your app. See here for the latest information: docs.djangoproject.com/en/1.9/ref/applications Jan 25, 2016 at 20:09
  • Is necessary to delete jobs? Because I can see queue raising every time app restarts. Aug 2, 2016 at 9:41
  • 1
    It would be useful to specify queue name using a queue_name argument of the scheduler.schedule() method if someone uses different than "default" queue. May 18, 2017 at 8:15
  • 1
    CAUTIOUS if you are running your django app with gunicorn or other webserver with multiple workers this approach will likely duplicate tasks in the schedule and they will be executed multiple times. Thus e.g. scheduled email will be sent twice (probably not desirable). Nov 10, 2022 at 16:32
9

I've added scheduling to a __init__ module in one of my project application (in terms of Django), but wrapped with small function which prevents queueing jobs twice or more. Scheduling strategy may be dependent of your specific needs (i.e. you may need additional checking for a job arguments).

Code that works for me and fit my needs:

import django_rq
from collections import defaultdict
import tasks

scheduler = django_rq.get_scheduler('default')

jobs = scheduler.get_jobs()
functions = defaultdict(lambda: list())

map(lambda x: functions[x.func].append(x.meta.get('interval')), jobs)

now = datetime.datetime.now()

def schedule_once(func, interval):
    """
    Schedule job once or reschedule when interval changes
    """
    if not func in functions or not interval in functions[func]\
            or len(functions[func])>1:

        # clear all scheduled jobs for this function
        map(scheduler.cancel, filter(lambda x: x.func==func, jobs))

        # schedule with new interval
        scheduler.schedule(now+datetime.timedelta(seconds=interval), func,
                interval=interval)

schedule_once(tasks.some_task_a, interval=60*5)
schedule_once(tasks.some_task_b, interval=120)

Also I've wrapped this snippet to avoid imports at the package level:

def init_scheduler():
    # paste here initialization code

init_scheduler()
1
  • 4
    I just ran into the hell that is 'scheduling in settings.py'. Apparently each time it gets imported, it re-adds the scheduled jobs. I had jobs that were supposed to fire once per hour stacking up in the queue 50 at a time.... ;) Aug 16, 2015 at 8:03
1

you should use django command to run schedule job https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/

like this

enter image description here

class Command(BaseCommand):

  def handle(self, *args, **options):
    scheduler = django_rq.get_scheduler('crontab_job')
    for job in scheduler.get_jobs():
        scheduler.cancel(job)
    # 定时任务例子1
    scheduler.cron(
        "*/3 * * * *",  # 每周一零点零时零分执行 0 0 * * 0    测试可以使用 */3 * * * * 每3分钟执行一次
        func=gong_an_job,  # Function to be queued
        kwargs={'msg': '我是王龙飞1,我喜欢修仙', 'number': 1},  # Keyword arguments passed into function when executed
        repeat=None,  # Repeat this number of times (None means repeat forever)
        queue_name='crontab_job',  # In which queue the job should be put in
        use_local_timezone=False  # Interpret hours in the local timezone
    )
    # 定时任务例子2
    scheduler.cron(
        "*/5 * * * *",  # 每周一零点零时零分执行 0 0 * * 0    测试可以使用 */3 * * * * 每3分钟执行一次
        func=gong_an_job,  # Function to be queued
        kwargs={'msg': '我是王龙飞222222,我喜欢修仙', 'number': 22222},  # Keyword arguments passed into function when executed
        repeat=None,  # Repeat this number of times (None means repeat forever)
        queue_name='crontab_job',  # In which queue the job should be put in
        use_local_timezone=False  # Interpret hours in the local timezone
    )

#create crontab job

python manage.py rq_crontab_job

#check crontab job and put crontab job to queue

python manage.py rqscheduler --queue crontab_job

#run crontab job

python manage.py rqworker crontab_job

I think the first answer is greate,but in multi-Progress enviroment may have some probelm,you should only run once to create crontab job !

1
  • 1
    Your are answering a very old question. Do you think that your answer improves over the other answers? If yes, please edit your response to clearly state this and show how the previous answers might not be relevant anymore. Also, please make an effort on the formatting.
    – mozway
    Jul 16, 2021 at 8:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.