Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function in background

I want to run a function independently. From the function I call, I want return without waiting for the other function ending.

I tried with threadind, but this will wait, the end.

thread = threading.Thread(target=myFunc)
thread.daemon = True
thread.start()
return 'something'

Is it possible to return immediately and the other process still run? Thanks for the Answers.

EDITED The working code looks like:

 import concurrent.futures 
 executor = concurrent.futures.ThreadPoolExecutor(2) 
 executor.submit(myFunc, arg1, arg2)
like image 574
Benjámin Gerván Avatar asked Feb 12 '16 08:02

Benjámin Gerván


People also ask

How do I run a Python function in the background?

We can configure a new daemon thread to execute a custom function that will perform a long-running task, such as monitor a resource or data. For example we might define a new function named background_task(). Then, we can configure a new threading. Thread instance to execute this function via the “target” argument.

How do I run a Python subprocess in the background?

import os pid = os. fork() if pid == 0: Continue to other code ... This will make the python process run in background. Save this answer.


2 Answers

You are more or less asking the following question:

Is it possible to run function in a subprocess without threading or writing a separate file/script

You have to change the example code from the link like this:

from multiprocessing import Process

def myFunc():
    pass  # whatever function you like

p = Process(target=myFunc)
p.start()  # start execution of myFunc() asychronously
print)'something')

p.start() is executed asychronously, i.e. 'something' is printed out immediately, no matter how time consuming the execution of myFunc() is. The script executes myFunc() and does not wait for it to finish.

like image 184
Gerhard Hagerer Avatar answered Sep 22 '22 03:09

Gerhard Hagerer


if I understood your request correctly, you might want to take a look on worker queues https://www.djangopackages.com/grids/g/workers-queues-tasks/

Basically it's not a good idea to offload the work to thread created in view, this is usually handled by having a pool of background workers (processes, threads) and the queue for incoming requests.

like image 29
Michal Vyskocil Avatar answered Sep 24 '22 03:09

Michal Vyskocil