Skip to main content
2 of 3
Added one more example
axel_ande
  • 2.1k
  • 13
  • 26

Usage of QgsTask and QgsTaskManager

I'm trying to test the new QgsTask and QgsTaskManager, I found some examples in the PullRequest in github. I modified it slightly and added a print(i) in the code bellow:

from qgis.core import QgsTask, QgsTaskManager
from time import sleep
import random
def run1(task,time):
   wait_time = time / 100.0
   sum = 0
   iterations = 0
   for i in range(101):
       sleep(wait_time)
       print(i)
        # use task.setProgress to report progress
        task.setProgress( i )
        sum += random.randint(0,100)
        iterations += 1
        # check task.isCancelled() to handle cancellation
        if task.isCancelled():
            stopped()
            return
        # raise expections to abort task
        #if random.randint(0,100) == 7:
        #    raise Exception('bad value!')
    # use task object to store results of calculations or operations
    task.result = [sum,iterations]

task=QgsTask.fromFunction('waste cpu', run1, 2)
mgr=QgsTaskManager()
mgr.addTask(task)
task.isFinished()

When I run this code in the Python console it returns 0 two times and then nothing more. I expected 101 printouts (0-100)? Afterwards I tried to see if it was finished with trying to call task.isFinished(), hence that gave me a RuntimeError: wrapped C/C++ object of type QgsTaskWrapper has been deleted.

In the end I would like use one QgsTask to run a time consuming script and one QgsTask to run a dialog (maybe a progressbar) telling the user that script is still running..

Any suggestion what I'm doing/thinking wrong or were to look at other examples?

EDIT: The problem was not only that there was two "L" in isCancel and start of QgsTaskManager, it was also that I tried to use print() within QgsTask. So I tried another approach with two GUIs that I tried in this repo. It is not working yet though :(. If I try to show a waiting message like this, the message will show, hence if try task.cancel() nothing happens since self.exec_() blocks the code until the I close the window. When I close the window the task is still running and then task.cancel() works as expected.

def run(self, task):
    self.LWatingMsgs.setText('test')
    self.show()
    self.exec_()
    running = True
    while running:
        if task.isCanceled():
            self.done(0)
            task.terminated()
            running = False
        else:
            sleep(1)
axel_ande
  • 2.1k
  • 13
  • 26