0

I would like my script to run a random query (fetched through my function getRandomQuery) every 5 seconds. However I want this to be done in an asynchronous way: I launch query1, wait 5s, launch query2 ect. query2 doesn't have to wait for the termination of query1 to start. When the result of a query is available, I want to print it.

This is my attempt so far:

from elasticsearch import AsyncElasticsearch
import glob
import asyncio
import random
import time

def main():

    es = AsyncElasticsearch("https://myElasticsearch", verify_certs=False, ssl_show_warn=False, request_cache=False)

    while (1):
        loop.create_task(execute_query(es))
        print("sleeping...")
        time.sleep(5)


async def execute_query(es):
    res = await es.search(index="myIndex", body = getRandomQuery())
    print("I'm done")
    print(res)

def getRandomQuery():
    ...

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

However this isn't working, all I see being printed is:

sleeping...
sleeping...
sleeping...
sleeping...
sleeping...
Mit94
  • 718
  • 8
  • 28
  • Related: https://stackoverflow.com/questions/34499400/how-to-add-a-coroutine-to-a-running-asyncio-loop – jarmod Sep 16 '21 at 14:37
  • I think that its related to the `time.sleep(5)` that is blocking all executions even if its async. I changed it to `await asyncio.sleep(5)` and it seems to be working fine this time. – Mit94 Sep 16 '21 at 15:24
  • Believe that you are correct because time.sleep(5) is blocking while asyncio.sleep(5) is non-blocking (per this [answer](https://stackoverflow.com/a/56730924/271415)). – jarmod Sep 16 '21 at 16:22

0 Answers0