Ask Your Question
1

How to run an awaitable/async function in Python RQ?

asked 2023-06-19 04:39:01 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-19 04:58:02 +0000

lakamha gravatar image

You can run an awaitable/async function in Python RQ using the asyncio library. Here's how to do it:

  1. First, you need to create an instance of the RQ worker with async=True parameter:
from rq import Worker
from rq import Queue
from redis import Redis

redis_conn = Redis()
queue = Queue('default', connection=redis_conn)
worker = Worker([queue], connection=redis_conn, async=True)
  1. Then, define your async function that needs to be run using async def keyword:
async def my_async_function():
    # do some async task
    return 'async task done'
  1. Now, add your function to the RQ job queue using asyncio:
import asyncio
from rq.job import Job

async def add_async_job_to_queue():
    job = await asyncio.create_task(queue.enqueue(my_async_function))
    return job

This will create an async job in RQ queue and return its job ID. You can use this ID to check the status of the job or to get its result.

  1. Finally, start the worker to execute the async job:
worker.work()

This will start the worker and it will execute the async jobs in the queue. You can stop the worker by pressing Ctrl+C.

Note: Keep in mind that you need to have an event loop running in your code to use async/await syntax.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-19 04:39:01 +0000

Seen: 19 times

Last updated: Jun 19 '23