This is an example of executing a function in the background. I was searching for an option to run a function in background along with the normal execution flow.


The main execution will continue in the same flow without waiting for the background function to complete and the function set for background execution will continue its execution in the background.


You can modify this code based on your requirement. Just replace the logic inside function under the @background annotation. Hope this tip helps 🙂


import time
import threading
def background(f):
'''
a threading decorator
use @background above the function you want to run in the background
'''
def backgrnd_func(*a, **kw):
threading.Thread(target=f, args=a, kwargs=kw).start()
return backgrnd_func
@background
def call_function(fun_name, count):
#This will print the count for every second
for val in range(1, count+1):
print("{} counts –> {}".format(fun_name, val))
time.sleep(1)
# start the background function
# note that with the @background decorator
# background function executes simultaneously
print "My name is Amal. This is the main thread execution"
call_function("Background Function One", 6)
call_function("Background Function Two", 6)
print "My name is Amal. The main thread reached here."