ThreadedTask

Methods

qconcurrency.threading_.ThreadedTask.__init__(…)
param callback:A function, method, or class that you would like to run in
qconcurrency.threading_.ThreadedTask.request_abort(…) Runs SignalManager._request_abort() .
qconcurrency.threading_.ThreadedTask.run() Runs callback( *args, **kwds ) in a separate thread.
qconcurrency.threading_.ThreadedTask.signal(…) Returns one of the QtCore.Signal s defined in signals.
qconcurrency.threading_.ThreadedTask.signalmgr() Returns SignalManager instance (QObject that will be
qconcurrency.threading_.ThreadedTask.start([…]) Queues this thread in a QtCore.QThreadPool

Documentation

class qconcurrency.threading_.ThreadedTask(callback, signals=None, *args, **kwds)[source]

Bases: PySide.QtCore.QRunnable

Bundles a callback method, it’s arguments, and a variable number of signals (with variable return-types) into a QtCore.QRunnable that can be safely queued in a QtCore.QThreadPool.

Every callback method must accept the keyword argument signalmgr. signalmgr is a QtCore.QObject that is instantiated with signals to communicate back with the UI thread, and the method SignalManager.handle_if_abort() which should be run periodically in your callback method to handle user-abort requests (issued by request_abort() ).

Example

Run function in QCoreApplication’s :py:obj:`QtCore.QThreadPool`

Handling early-exit by periodically (at safe points) checking if task.request_abort() has been run.

def long_running_job( jobid, signalmgr=None ):
    for i in range(5):
        signalmgr.handle_if_abort()   # exit early, if user-abort requested
        time.sleep(1)
    print('finished job %s' % jobid )

task = ThreadedTask(
    callable = long_running_job,
    jobid    = 1
)
task.start()

Create signals that can be used within the thread.

QtCore.QRunnable objects (which get used in a QtCore.QThreadPool ) cannot have signals attached to them. In order for this to work you must create a QtCore.QObject with the signals that can be passed to the thread. This all gets done behind the scenes with a ThreadedTask .

def long_running_job( signalmgr=None ):
    signalmgr.log_message.emit('started job...')
    signalmgr.set_title.emit('My Title', 'my description')
    signalmgr.status_changed.emit()

def printargs(*args):
    print( args )


task = ThreadedTask(                      ### Roughly Equivalent to:
    callback = long_running_job,          #
    signals  = {                          #  class SignalManager( QtCore.QObject ):
        'status_changed': None,           #      status_changed = QtCore.Signal()
        'log_message':    str,            #      log_message    = QtCore.Signal(str)
        'set_title':     (str,str),       #      set_title      = QtCore.Signal(str,str)
    },                                    #
)                                         #
task.signal('set_title').connect(   printargs )
task.signal('log_message').connect( printargs )
task.start()

Handle successful returns, and unhandled exceptions

ThreadedTask have builtin signals returned, and exception, that are emitted automatically. You may emit the output of your callback in returned, only if you override the returned signal in the signals argument.

def long_running_job( signalmgr=None ):
    pass

def run_on_exit(*args,**kwds):
    pass


task = ThreadedTask(
    callback = long_running_job,
)
task.signal('returned').connect(run_on_exit)
task.signal('exception').connect(run_on_exit)
task.start()
__init__(callback, signals=None, *args, **kwds)[source]
Parameters:
  • callback (callable) – A function, method, or class that you would like to run in a separate thread.
  • signals (dict, optional) –

    Dictionary of signal-names, and the datatypes they will emit. Signals defined here will override any default signals.

    {
        # signal-name #  # datatype #   # equivalent-to #
    
        ‘add_item’:       (int,str),    #: QtCore.Signal(int,str)
        ‘add_progress’:   int,          #: QtCore.Signal(int)
        ‘returned’:       None,         #: QtCore.Signal()
    }
    
  • *args/**kwds

    Any additional arguments/keyword-arguments are passed to the callback in run()

request_abort(*args, **kwds)[source]

Runs SignalManager._request_abort() . (your callback will still need to periodically run SignalManager.handle_if_abort() at safe points to exit).

run()[source]

Runs callback( *args, **kwds ) in a separate thread. This method will be called automatically by the QtCore.QThreadPool when queued (see start())

If an unhandled exception is raised during the callback’s execution, the signal exception is called. Otherwise the signal returned is emitted when the method completes.

If you desire to catch the return-value of the callback, simply define the expected return-value for it in the argument signals.

task = ThreadedTask(
    callback = mycallback,
    signals  = {'returned': (int,int)},  #: mycallback is now expected to return 2x integers
)
signal(signal_name)[source]

Returns one of the QtCore.Signal s defined in signals. See documentation in __init__().

signalmgr()[source]

Returns SignalManager instance (QObject that will be passed to separate thread, and stores all signals the thread will use to communicate back to the UI thread.)

start(expiryTimeout=-1, threadpool=None)[source]

Queues this thread in a QtCore.QThreadPool (by default QtCore.QThreadPool.globalInstance() )

Parameters:
  • expiryTimeout (int, optional) – Thread that unused for N milliseconds are considered expired and will exit. By default, no exipiryTimeout is set (-1).
  • threadpool (QtCore.QThreadPool, optional) – By default, this ThreadedTask will be queued in the QCoreApplication’s global threadpool. If you would prefer to assign another, you may specify it here.