Aitor Martin
Aitor Martin

Reputation: 734

How to execute a Python function within a function and not stop the execution

I'm trying to accomplish something without using threading

I'd like to execute a function within a function, but I dont want the first function's flow to stop. Its just a procedure and I don't expect any return and I also need this to keep the execution for some reasons.

Here is a snippet code of what I'd like to do:

function foo():

    a = 5

    dosomething() 
    # I dont wan't to wait until dosomething finish. Just call and follow it

    return a

Is there any way to do this?

Thanks in advance.

Upvotes: 1

Views: 506

Answers (2)

aifarfa
aifarfa

Reputation: 3939

You can use https://docs.python.org/3/library/concurrent.futures.html to achieve fire-and-forget behavior.

import concurrent.futures

def foo():
    a = 5

    with ThreadPoolExecutor(max_workers=1) as executor:
        future = executor.submit(dosomething)
        future.add_done_callback(on_something_done)
        #print(future.result())

    #continue without waiting dosomething()
    #future.cancel() #To cancel dosomething
    #future.done() #return True if done.

    return a

def on_something_done(future):
    print(future.result())

[updates]

concurrent.futures is built-in since python 3

for Python 2.x you can download futures 2.1.6 here

Upvotes: 1

agconti
agconti

Reputation: 18093

Python is synchronous, you'll have to use asynchronous processing to accomplish this.

While there are many many ways that you can execute a function asynchronously, one way is to use python-rq. Python-rq allows you to queue jobs for processing in the background with workers. It is backed by Redis and it is designed to have a low barrier to entry. It should be integrated in your web stack easily.

For example:

from rq import Queue, use_connection
def foo():
   use_connection()
   q = Queue()
   # do some things
   a = 5
   # now process something else asynchronously
   q.enqueue(do_something)
   # do more here
   return a

Upvotes: 1

Related Questions