【问题标题】:Calling methods asynchronously异步调用方法
【发布时间】:2015-11-28 12:04:15
【问题描述】:

我正在尝试在 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)

【问题讨论】:

标签: python python-2.7 asynchronous backgroundworker


【解决方案1】:

在后台线程中运行方法:

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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多