Class: QgsTask

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.

Note

This is an abstract class, with methods which must be implemented by a subclass.

The following methods must be implemented: run()

Class Hierarchy

Inheritance diagram of qgis.core.QgsTask

Base classes

QObject

Subclasses

QgsCopyFileTask

Task to copy a file on disk.

QgsMapHitTestTask

Executes a QgsMapHitTest in a background thread.

QgsMapRendererTask

QgsTask task which draws a map to an image file or a painter as a background task.

QgsNetworkContentFetcherTask

Handles HTTP network content fetching in a background task.

QgsPointCloudLayerExporterTask

QgsTask task which performs a QgsPointCloudLayerExporter layer export operation as a background task.

QgsProcessingAlgRunnerTask

QgsTask task which runs a QgsProcessingAlgorithm in a background task.

QgsProfileExporterTask

Handles exports of elevation profiles in various formats in a background task.

QgsProviderSublayerTask

A QgsTask which retrieves sublayer details for a URI.

QgsProxyProgressTask

A QgsTask shell which proxies progress reports.

QgsRasterFileWriterTask

QgsTask task which performs a QgsRasterFileWriter layer saving operation as a background task.

QgsTaskWithSerialSubTasks

A task that is composed of sub-tasks to be executed in a serial way.

QgsVectorFileWriterTask

QgsTask task which performs a QgsVectorFileWriter layer saving operation as a background task.

QgsVectorLayerExporterTask

QgsTask task which performs a QgsVectorLayerExporter layer export operation as a background task.

QgsVectorLayerFeatureCounter

Counts the features in a QgsVectorLayer in task.

QgsVirtualLayerTask

Initializes a virtual layer with postpone mode activated and reloads the data in a separate thread.

QgsTaskWrapper

QgsVectorWarperTask

A task for warping a vector layer in a background thread.

Abstract Methods

run

Performs the task's operation.

Methods

addSubTask

Adds a subtask to this task.

canCancel

Returns True if the task can be canceled.

dependentLayers

Returns the list of layers on which the task depends.

description

Returns the task's description.

elapsedTime

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

flags

Returns the flags associated with the task.

hold

Places the task on hold.

isActive

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

isCanceled

Will return True if task should terminate ASAP.

progress

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

setDependentLayers

Sets a list of layers on which the task depends.

setDescription

Sets the task's description.

setProgress

Sets the task's current progress.

status

Returns the current task status.

unhold

Releases the task from being held.

waitForFinished

Blocks the current thread until the task finishes or a maximum of timeout milliseconds.

Virtual Methods

In PyQGIS, only methods marked as virtual can be safely overridden in a Python subclass of QgsTask. See the FAQ for more details.

cancel

Notifies the task that it should terminate.

finished

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).

Static Methods

fromFunction

Creates a new QgsTask task from a python function.

Signals

begun

Will be emitted by task to indicate its commencement.

progressChanged

Will be emitted by task when its progress changes.

statusChanged

Will be emitted by task when its status changes.

taskCompleted

Will be emitted by task to indicate its successful completion.

taskTerminated

Will be emitted by task if it has terminated for any reason other then completion (e.g., when a task has been canceled or encountered an internal error).

Attributes

AllFlags

CanCancel

CancelWithoutPrompt

Complete

Hidden

OnHold

ParentDependsOnSubTask

Queued

Running

Silent

SubTaskIndependent

Terminated

class qgis.core.QgsTask[source]

Bases: QObject

__init__(description: str | None = '', flags: QgsTask.Flags | QgsTask.Flag = QgsTask.AllFlags)

Constructor for QgsTask.

Parameters:
  • description (Optional[str] = '') – text description of task

  • flags (Union[QgsTask.Flags, QgsTask.Flag] = QgsTask.AllFlags) – task flags

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

Bases: int

class Flags
class Flags(f: QgsTask.Flags | QgsTask.Flag)
class Flags(a0: QgsTask.Flags)

Bases: object

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

Bases: int

SubTaskIndependent = 0
class TaskStatus

Bases: int

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

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 (Optional[QgsTask])

  • dependencies (Iterable[QgsTask] = [])

  • subTaskDependency (QgsTask.SubTaskDependency = QgsTask.SubTaskIndependent)

signal begun[source]

Will be emitted by task to indicate its commencement.

Note

derived classes should not emit this signal directly, it will automatically be emitted when the task begins

canCancel(self) bool[source]

Returns True if the task can be canceled.

Return type:

bool

virtual cancel(self)[source]

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()

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[source]

Returns the task’s description.

Return type:

str

elapsedTime(self) int[source]

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

The value is undefined for tasks which have not begun.

Added in version 3.4.

Return type:

int

virtual finished(self, result: bool)[source]

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[source]

Returns the flags associated with the task.

Return type:

QgsTask.Flags

static fromFunction(description: str, function: Callable, *args, on_finished: Callable | None = None, flags=2, **kwargs) QgsTask

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)[source]

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[source]

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

Return type:

bool

isCanceled(self) bool[source]

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

progress(self) float[source]

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

Return type:

float

signal progressChanged(progress: float)[source]

Will be emitted by task when its progress changes.

Parameters:

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

Note

derived classes should not emit this signal directly, instead they should call setProgress()

abstract run(self) bool[source]

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

setDependentLayers(self, dependentLayers: Iterable[QgsMapLayer])[source]

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 | None)[source]

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.

Added in version 3.10.

Parameters:

description (Optional[str])

setProgress(self, progress: float)[source]

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[source]

Returns the current task status.

Return type:

QgsTask.TaskStatus

signal statusChanged(status: int)[source]

Will be emitted by task when its status changes.

Parameters:

status (int) – new task status

Note

derived classes should not emit this signal directly, it will automatically be emitted

signal taskCompleted[source]

Will be emitted by task to indicate its successful completion.

Note

derived classes should not emit this signal directly, it will automatically be emitted

signal taskTerminated[source]

Will be emitted by task if it has terminated for any reason other then completion (e.g., when a task has been canceled or encountered an internal error).

Note

derived classes should not emit this signal directly, it will automatically be emitted

unhold(self)[source]

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[source]

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