Hi,

https://qgis.org/pyqgis/3.30/core/QgsTask.html says

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

How are we supposed to "terminate" a task properly?

If we check for task.isCanceled() (or call task.cancel() ourselves for testing) and simply return:

- QGIS will still show a notification that the "Task completed" (instead of "Task failed") (https://github.com/qgis/QGIS/blob/d3d0431685883b837caa571ad7282828cfbde65e/src/app/qgisapp.cpp#L15707)

- The taskTerminated signal is not emitted. But the taskCompleted signal is emitted.

- The task's status is QgsTask.Complete

There is no obvious way to "terminate" the task from the Python side. We cannot set the task's status attribute to QgsTask.Terminated (https://qgis.org/pyqgis/3.30/core/QgsTask.html#qgis.core.QgsTask.Terminated).


If an exception happens in the task then it seems to terminate "properly", i.e. its status will be QgsTask.Terminated, the taskTerminated signal is emitted and a notification "Task failed" is shown. This is the only way I found today to get into this state. I have not found this documented and only by accident...


Example for a QgsTask.fromFuncction(..., flags=QgsTask.CanCancel), uncomment one of the final lines:

def foo(task):
        time.sleep(6)  # must be >= minTaskLengthForSystemNotification (5 by default)
        #task.cancel(); return  # -> Task complete
        #raise Exception("fail plz")  # -> Task failed


It feels like a bug to me (either task.cancel should directly set its status to QgsTask.Terminated or we should have a task.setStatus() method) but everything in and around QgsTask is fairly opaque and hard to grasp so maybe I am just missing something obvious.

Cheers, Hannes


PS: I did not test the example function in a clean environment, in my test cases I have code like this as methods of a class.

--
Johannes Kröger / GIS-Entwickler/-Berater

---------------------------------------------
Aufwind durch Wissen!
Web-Seminare und Online-Schulungen
bei der www.foss-academy.com
---------------------------------------------

WhereGroup GmbH
c/o KK03 GmbH
Lange Reihe 29
20099 Hamburg
Germany

Tel: +49 (0)228 / 90 90 38 - 36
Fax: +49 (0)228 / 90 90 38 - 11

johannes.kroe...@wheregroup.com
www.wheregroup.com
Geschäftsführer:
Olaf Knopp, Peter Stamm
Amtsgericht Bonn, HRB 9885
-------------------------------

_______________________________________________
QGIS-Developer mailing list
QGIS-Developer@lists.osgeo.org
List info: https://lists.osgeo.org/mailman/listinfo/qgis-developer
Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-developer

Reply via email to