异步调用方法

时间:2015-09-02 20:15:55

标签: python python-2.7 asynchronous backgroundworker

我试图在python 2.7中编写后台服务,它可以同时调用多个方法,其中每个方法可能需要更长的时间才能完成。

我想异步调用所有方法而不等待工作完成。

样例想法:

def run(self):
    while(True):
        Job1()
        Job2()
        Job3()
        time.sleep(10)
        print ("After sleep")

def Job1(self):
    a = [1,2,3,4,5,6,7,8,9]
    for i in a:
        print "Job 1 : " + str(i)

def Job2(self):
    a = [1,2,3,4,5,6,7,8,9]
    for i in a:
        print "Job 2 : " + str(i)

def Job3(self):
    a = [1,2,3,4,5,6,7,8,9]
    for i in a:
        print "Job 3 : " + str(i)

1 个答案:

答案 0 :(得分:0)

在后台线程中运行方法:

import threading
...
thread = threading.Thread(target=self.methodname, args=())
        thread.daemon = True     # Daemonize thread
        thread.start()           # Start the execution

来源:http://sebastiandahlgren.se/2014/06/27/running-a-method-as-a-background-thread-in-python/