简体   繁体   中英

Running a background thread in python

All the examples I've been able to get to don't really address my problem, of having a certain procedure in the background constantly looping, while the rest of the program continues.

Here is a simple example of a method that works, using _thread:

import _thread
import time


def countSeconds():
    time.sleep(1)
    print("Second")
    _thread.start_new(countSeconds, ())

def countTenSeconds():
    time.sleep(10)
    print("Ten seconds passed")
    _thread.start_new(countTenSeconds, ())


_thread.start_new(countSeconds, ())
_thread.start_new(countTenSeconds, ())

Ignoring the obvious fact that we could track the seconds, and just print something different if it's a multiple of ten, how would I go about creating this more efficiently.

In my actual program, the threading seems to be guzzling RAM, I assume from creating multiple instance of the thread. Do I have to "start_new" thread at the end of each procedure?

Thanks for any help.

All the examples I've been able to get to don't really address my problem Which examples?

This does work for me.

import threading

def f():
    import time
    time.sleep(1)
    print "Function out!"

t1 = threading.Thread(target=f)

print "Starting thread"
t1.start()
time.sleep(0.1)
print "Something done"
t1.join()
print "Thread Done"

You're asking for a repeated thread, I don't get what exactly you need, this might work:

import threading
var = False
def f():
    import time
    counter = 0
    while var:
        time.sleep(0.1)
        print "Function {} run!".format(counter)
        counter+=1

t1 = threading.Thread(target=f)

print "Starting thread"
var = True
t1.start()
time.sleep(3)
print "Something done"
var = False
t1.join()
print "Thread Done"

use the threading.timer to continue launching a new background thread

import threading
import time


def countSeconds():
    print("Second")
    threading.Timer(1, countSeconds).start()

def countTenSeconds():
    print("Ten seconds passed")
    threading.Timer(10, countTenSeconds).start()


threading.Timer(1, countSeconds).start()
threading.Timer(10, countTenSeconds).start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM