How to plan a one-time event at Django in Heroku?

My question is about developing the software needed to schedule an event that will run once in the future in a distributed Heroku environment.

I believe that it is better to write what I want to achieve, but I certainly did my research and could not understand myself even after two hours of work.

Let's say in my views.pyI have a function:

def after_6_hours():
    print('6 hours passed.')


def create_game():
    print('Game created')
    # of course time will be error, but that just an example
    scheduler.do(after_6_hours, time=now + 6)

so I want to execute the function after_6_hours6 hours after the call create_game. Now, as you can see, this function is determined from regular files clock.pyor task.pyor etc etc.

Now, how can I all my application running in Heroku, all the time, and be able to add this task to the queue of this imaginary-for-now- library scheduler?

On the side of the note, I cannot use the Temokorizer add-on from Heroku. The combination of APScheduler and Python rq looked promising, but the examples are trivial, everything is planned in one file in clock.py, and I just donโ€™t know how to link everything together with the setup I have. Thanks in advance!

+4
source share
1 answer

Heroku Django Web Dyno, , , ( , ):

after_hours.py, , ( , ).

def after_6_hours():
        print('6 hours passed.')

views.py, rq ( , rq, ) rq-scheduler:

from redis import Redis
from rq_scheduler import Scheduler
from datetime import timedelta

from after_hours import after_6_hours

def create_game():
    print('Game created')

    scheduler = Scheduler(connection=Redis()) # Get a scheduler for the "default" queue
    scheduler.enqueue_in(timedelta(hours=6), after_6_hours) #schedules the job to run 6 hours later.

create_game() after_6_hours() 6 .

: Redis Heroku, Redis To Go .

- rqscheduler, Redis, , - , ( rq).

, Worker Dyno after_hours.py

def after_6_hours():
    print('6 hours passed.')
    #Better return something

worker.py:

import os

import redis
from rq import Worker, Queue, Connection

from after_hours import after_6_hours

listen = ['high', 'default', 'low'] # while scheduling the task in views.py we sent it to default

redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')

conn = redis.from_url(redis_url)

if __name__ == '__main__':
    with Connection(conn):
        worker = Worker(map(Queue, listen))
        worker.work()

worker.py

python worker.py

(afer_6_hours ) Worker Dyno. , , (after_hours.py ) . rq docs

, .

, docs .

, - ( X Y), , .

 q = Queue('low', connection=redis_conn)
 q.enqueue('my_package.my_module.my_func', 3, 4)

, rq-scheduler .

/ (Celery/RabbitMQ, APScheduler ..), .

+3

All Articles