You can modify this code based on your requirement. Just replace the logic inside function under the @background annotation. Hope this tip helps 🙂
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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." |
Dear,
You have not put print statements in brackets. This might throw an error. As print is a method and statement should be passed within brackets.
Hi Rohan,
Thank you for the feedback. At the time of writing this article I was using Python 2.x which does not need brackets in print statement. I will update this article for Python 3.