【问题标题】:Python execute task [duplicate]Python执行任务[重复]
【发布时间】:2016-01-27 07:53:02
【问题描述】:

我有一个带有无限期阻塞任务方法的 Python 类

class A(object):
   def __init__(self):
       # start task

   def task(self):
       while True:
           #do some work

我想在 A 的构造函数中开始执行任务。由于任务阻塞,它可能需要在自己的线程中运行。如何在 Python 2.7 中做到这一点?

【问题讨论】:

标签: python task


【解决方案1】:

就像 cmets 中提到的,有一个模块 threading 似乎完全适合您的任务。示例:

import threading

class A(object):
   def __init__(self):
       threading.Thread(target=self.task).start()

   def task(self):
       print 'Hello from a Thread'

a = A()

# output: 'Hello from a Thread'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2012-01-04
    相关资源
    最近更新 更多