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¶
Base classes¶
Subclasses¶
Task to copy a file on disk. |
|
Executes a |
|
|
|
Handles HTTP network content fetching in a background task. |
|
|
|
|
|
Handles exports of elevation profiles in various formats in a background task. |
|
A |
|
A |
|
|
|
A task that is composed of sub-tasks to be executed in a serial way. |
|
|
|
|
|
Counts the features in a |
|
Initializes a virtual layer with postpone mode activated and reloads the data in a separate thread. |
|
A task for warping a vector layer in a background thread. |
Abstract Methods
Performs the task's operation. |
Methods
Adds a subtask to this task. |
|
Returns |
|
Returns the list of layers on which the task depends. |
|
Returns the task's description. |
|
Returns the elapsed time since the task commenced, in milliseconds. |
|
Returns the flags associated with the task. |
|
Places the task on hold. |
|
Returns |
|
Will return |
|
Returns the task's progress (between 0.0 and 100.0) |
|
Sets a list of layers on which the task depends. |
|
Sets the task's description. |
|
Sets the task's current progress. |
|
Returns the current task status. |
|
Releases the task from being held. |
|
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.
Notifies the task that it should terminate. |
|
If the task is managed by a |
Static Methods
Creates a new |
Signals
Will be emitted by task to indicate its commencement. |
|
Will be emitted by task when its progress changes. |
|
Will be emitted by task when its status changes. |
|
Will be emitted by task to indicate its successful completion. |
|
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
- 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 aQgsTaskManager
, 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.
- 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
- 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
- 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.
See also
- Return type:
List[QgsMapLayer]
- 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:
- 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
- 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.
See also
- Parameters:
dependentLayers (Iterable[QgsMapLayer])
- setDescription(self, description: str | None)[source]¶
Sets the task’s
description
. This must be called before adding the task to aQgsTaskManager
, 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:
- 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
- waitForFinished(self, timeout: int = 30000) bool [source]¶
Blocks the current thread until the task finishes or a maximum of
timeout
milliseconds. Iftimeout
is0
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 andTrue
in any other case.- Parameters:
timeout (int = 30000)
- Return type:
bool