Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a function several times asynchronously and get first result

I have a function get_data(request) that requests some data to a server. Every time this function is called, it request data to a different server. All of them should return the same response.

I would like to get the response as soon as possible. I need to create a function that calls get_data several times, and returns the first response it gets.

EDIT:

I came up with an idea of using multithreading.Pipe(), but I have the feeling this is a very bad way to solve it, what do you think?:

def get_data(request, pipe):
    data = # makes the request to a server, this can take a random amount of time
    pipe.send(data)

def multiple_requests(request, num_servers):
    my_pipe, his_pipe = multithreading.Pipe()

    for i in range(num_servers):
        Thread(target = get_data, args = (request,his_pipe)).start()

    return my_pipe.recv()

multiple_requests("the_request_string", 6)

I think this is a bad way of doing it because you are passing the same pipe to all threads, and I don't really know but I guess that has to be very unsafe.

like image 293
Jorky10 Avatar asked Dec 09 '15 05:12

Jorky10


People also ask

How do you make a function run multiple times?

Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.

How do you call multiple async functions?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).

Can we call a function multiple times?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.


1 Answers

I think redis rq will be good for it. get_data is a job what you put in the queue six times. Jobs executes async, in the docs your also can read how to operate with results.

like image 98
fedorshishi Avatar answered Oct 11 '22 14:10

fedorshishi