BackgroundWorker的在python

问题描述 投票:3回答:2

我是一个没有经验的Python程序员。

是否有这样它开始于程序启动和关闭时程序近距离使用BackgroundWorker的一种方式?

我想它来观看一个按钮,按下按钮时,返回1。因此,尽管在运行时按钮= 1个按钮必须做“这个”程序。

谁能帮我这个?

python backgroundworker
2个回答
7
投票

将是有意义的主程序中启动一个单独的线程做背景什么。作为一个例子检查下面的相当简单的代码:

import threading
import time

#Routine that processes whatever you want as background
def YourLedRoutine():
    while 1:
        print 'tick'
        time.sleep(1)

t1 = threading.Thread(target=YourLedRoutine)
#Background thread will finish with the main program
t1.setDaemon(True)
#Start YourLedRoutine() in a separate thread
t1.start()
#You main program imitated by sleep
time.sleep(5)

0
投票

对于Python 3.3,Thread构造有daemon说法。康斯坦丁的答复工作,但我喜欢只需要一条线启动一个线程的简洁:

import threading, time

MAINTENANCE_INTERVAL = 60

def maintenance():
    """ Background thread doing various maintenance tasks """
    while True:
        # do things...
        time.sleep(MAINTENANCE_INTERVAL)

threading.Thread(target=maintenance, daemon=True).start()

作为documentation mentions,守护线程一旦主线程退出退出,所以你仍然需要保持你的主线程繁忙,而后台工作做的事情。就我而言,我启动线程后启动Web服务器。

© www.soinside.com 2019 - 2024. All rights reserved.