Class: QgsTask

class qgis.core.QgsTask

Bases: PyQt5.QtCore.QObject

Abstract base class for long running background tasks. Tasks can be controlled directly, or added to a QgsTaskManager for automatic management.

Derived classes should implement the process they want to execute in the background within the run() method. This method will be called when the task commences (ie via calling run() ).

Long running tasks should periodically check the isCanceled() flag to detect if the task has been canceled via some external event. If this flag is True then the task should clean up and terminate at the earliest possible convenience.

New in version 3.0.

QgsTask(description: str = ‘’, flags: Union[QgsTask.Flags, QgsTask.Flag] = QgsTask.AllFlags) Constructor for QgsTask.

Parameters:
AllFlags = 2
CanCancel = 2
CancelWithoutPrompt = 4
Complete = 3
class Flag

Bases: int

class Flags
class Flags(Union[QgsTask.Flags, QgsTask.Flag])
class Flags(QgsTask.Flags)

Bases: sip.wrapper

Hidden = 8
OnHold = 1
ParentDependsOnSubTask = 1
Queued = 0
Running = 2
Silent = 16
class SubTaskDependency

Bases: int

SubTaskIndependent = 0
class TaskStatus

Bases: int

baseClass

alias of QgsTask

Terminated = 4
addSubTask(self, subTask: QgsTask, dependencies: Iterable[QgsTask] = [], subTaskDependency: QgsTask.SubTaskDependency = QgsTask.SubTaskIndependent)

Adds a subtask to this task.

Subtasks allow a single task to be created which consists of multiple smaller tasks. Subtasks are not visible or indepedently controllable by users. Ownership of the subtask is transferred. Subtasks can have an optional list of dependent tasks, which must be completed before the subtask can begin. By default subtasks are considered independent of the parent task, ie they can be run either before, after, or at the same time as the parent task. This behavior can be overridden through the subTaskDependency argument. Note that subtasks should NEVER be dependent on their parent task, and violating this constraint will prevent the task from completing successfully.

The parent task must be added to a QgsTaskManager for subtasks to be utilized. Subtasks should not be added manually to a QgsTaskManager, rather, only the parent task should be added to the manager.

Subtasks can be nested, ie a subtask can legally be a parent task itself with its own set of subtasks.

Parameters:
  • subTask (QgsTask) –

  • dependencies (Iterable[QgsTask] = []) –

  • subTaskDependency (QgsTask.SubTaskDependency = QgsTask.SubTaskIndependent) –

begun

pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

Parameters:
  • name (str = ...) –

  • revision (int = ...) –

  • arguments (Sequence = ...) –

Return type:

PYQT_SIGNAL

canCancel(self) bool

Returns True if the task can be canceled.

Return type:

bool

cancel(self)

Notifies the task that it should terminate. Calling this is not guaranteed to immediately end the task, rather it sets the isCanceled() flag which task subclasses can check and terminate their operations at an appropriate time. Any subtasks owned by this task will also be canceled. Derived classes must ensure that the base class implementation is called from any overridden version.

See also

isCanceled()

childEvent(self, QChildEvent)
connectNotify(self, QMetaMethod)
customEvent(self, QEvent)
dependentLayers(self) List[QgsMapLayer]

Returns the list of layers on which the task depends. The task will automatically be canceled if any of these layers are about to be removed.

Return type:

List[QgsMapLayer]

description(self) str

Returns the task’s description.

Return type:

str

disconnectNotify(self, QMetaMethod)
elapsedTime(self) int

Returns the elapsed time since the task commenced, in milliseconds.

The value is undefined for tasks which have not begun.

New in version 3.4.

Return type:

int

finished(self, result: bool)

If the task is managed by a QgsTaskManager, this will be called after the task has finished (whether through successful completion or via early termination). The result argument reflects whether the task was successfully completed or not. This method is always called from the main thread, so it is safe to create widgets and perform other operations which require the main thread. However, the GUI will be blocked for the duration of this method so tasks should avoid performing any lengthy operations here.

Parameters:

result (bool) –

flags(self) QgsTask.Flags

Returns the flags associated with the task.

Return type:

QgsTask.Flags

static fromFunction(description, function, *args, on_finished=None, flags=2, **kwargs)

Creates a new QgsTask task from a python function.

Example:

def calculate(task):

# pretend this is some complex maths and stuff we want # to run in the background return 5*6

def calculation_finished(exception, value=None):
if not exception:
iface.messageBar().pushMessage(

‘the magic number is {}’.format(value))

else:
iface.messageBar().pushMessage(

str(exception))

task = QgsTask.fromFunction(‘my task’, calculate,

on_finished=calculation_finished)

QgsApplication.taskManager().addTask(task)

hold(self)

Places the task on hold. If the task in not queued (ie it is already running or has finished) then calling this has no effect. Calling this method only has an effect for tasks which are managed by a QgsTaskManager.

See also

unhold()

isActive(self) bool

Returns True if the task is active, ie it is not complete and has not been canceled.

Return type:

bool

isCanceled(self) bool

Will return True if task should terminate ASAP. If the task reports the CanCancel flag, then derived classes’ run() methods should periodically check this and terminate in a safe manner.

Return type:

bool

isSignalConnected(self, QMetaMethod) bool
progress(self) float

Returns the task’s progress (between 0.0 and 100.0)

Return type:

float

progressChanged

pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

Parameters:
  • name (str = ...) –

  • revision (int = ...) –

  • arguments (Sequence = ...) –

Return type:

PYQT_SIGNAL

receivers(self, PYQT_SIGNAL) int
run(self) bool

Performs the task’s operation. This method will be called when the task commences (ie via calling start() ), and subclasses should implement the operation they wish to perform in the background within this method.

A task must return a boolean value to indicate whether the task was completed successfully or terminated before completion.

Return type:

bool

sender(self) QObject
senderSignalIndex(self) int
setDependentLayers(self, dependentLayers: Iterable[QgsMapLayer])

Sets a list of layers on which the task depends. The task will automatically be canceled if any of these layers are about to be removed.

Parameters:

dependentLayers (Iterable[QgsMapLayer]) –

setDescription(self, description: str)

Sets the task’s description. This must be called before adding the task to a QgsTaskManager, changing the description after queuing the task has no effect.

New in version 3.10.

Parameters:

description (str) –

setProgress(self, progress: float)

Sets the task’s current progress. The derived class should call this method whenever the task wants to update its progress. Calling will automatically emit the progressChanged signal.

Parameters:

progress (float) – percent of progress, from 0.0 - 100.0

status(self) QgsTask.TaskStatus

Returns the current task status.

Return type:

QgsTask.TaskStatus

statusChanged

pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

Parameters:
  • name (str = ...) –

  • revision (int = ...) –

  • arguments (Sequence = ...) –

Return type:

PYQT_SIGNAL

taskCompleted

pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

Parameters:
  • name (str = ...) –

  • revision (int = ...) –

  • arguments (Sequence = ...) –

Return type:

PYQT_SIGNAL

taskTerminated

pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

Parameters:
  • name (str = ...) –

  • revision (int = ...) –

  • arguments (Sequence = ...) –

Return type:

PYQT_SIGNAL

timerEvent(self, QTimerEvent)
unhold(self)

Releases the task from being held. For tasks managed by a QgsTaskManager calling this will re-add them to the queue. If the task in not currently being held then calling this has no effect.

See also

hold()

waitForFinished(self, timeout: int = 30000) bool

Blocks the current thread until the task finishes or a maximum of timeout milliseconds. If timeout is 0 the thread will be blocked forever. In case of a timeout, the task will still be running. In case the task already is finished, the method will return immediately while returning ``True``.

The result will be False if the wait timed out and True in any other case.

Parameters:

timeout (int = 30000) –

Return type:

bool