user5832974
user5832974

Reputation:

Python functions run as background processes

I know there are ways of making a program wait for a function to finish, but is there a way to make the function, once called, to carry on in the background of a program.

This might be especially useful if you were making a program timer, like the one below.

import time
count = 0    
def timer():
    while True():
        time.sleep(60)
        count += 1            
        print("This program has now been running for " + str(count) + " minutes"
timer() # Carry this function out in the background
print("Hello! Welcome to the program timer!")
name = raw_input("What is your name?")
print("Nice to meet you, " + name + "!")
# More stuff here...

I hope there is a way to do background processes in python.

Upvotes: 5

Views: 25526

Answers (2)

Danny Staple
Danny Staple

Reputation: 7332

This sounds like threading.

The threading module is relatively simple, but beware doing any CPU bound activities that way. With lots of timers and sleeps, or IO bound then this is fine.

Threading module example:

import time
from threading import Thread

def timer(name):
    count = 0
    while True:
        time.sleep(60)
        count += 1            
        print("Hi " + name + "This program has now been running for " + str(count) + " minutes.")

print("Hello! Welcome to the program timer!")
name = raw_input("What is your name?")
print("Nice to meet you, " + name + "!")
background_thread = Thread(target=timer, args=(name,))
background_thread.start()

To Clarify - relatively simple compared with the multiprocessing module - which you may want to look at if your background activity is CPU heavy.

The python docs have a good tutorial on this at: https://docs.python.org/2/library/threading.html#thread-objects

Upvotes: 13

Avihoo Mamka
Avihoo Mamka

Reputation: 4786

You can use thread for this.

From Wikipedia:

In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.[1] The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process. Multiple threads can exist within one process, executing concurrently (one starting before others finish) and share resources such as memory, while different processes do not share these resources. In particular, the threads of a process share its instructions (executable code) and its context (the values of its variables at any given time).

You can use this:

import threading

t1 = threading.Thread(target=timer)
t1.start()
t1.join()

The Thread class also provides start() and join() methods to control the starting of a thread and to provide a mechanism for waiting until the thread has finished execution (i.e. the end of run() method is reached).

Upvotes: 3

Related Questions