0

I am trying to create a price ticker which refreshes every 2 seconds.

how to cancel the previous thread after a new one was created (a new one is created after the run_worker() was called)

I was trying to access somehow the self._flag from outside to close the thread, but how to access the currently running one and close it ?

def run_worker(self):
    print("run_worker")
    symbol = str(self.ui.pair_combo.currentText())
    worker = Worker(self.execute_this_fn, symbol)
    worker.signals.result.connect(self.print_output)
    worker.signals.finished.connect(self.thread_complete)
    self.threadpool.start(worker)

class WorkerSignals(QObject):
    finished = pyqtSignal()
    error = pyqtSignal(tuple)
    result = pyqtSignal(object)


class Worker(QRunnable):
    def __init__(self, fn, *argv, **kwargs):
        super(Worker, self).__init__()
        self.fn = fn
        self.argv = argv
        self.kwargs = kwargs
        self.signals = WorkerSignals()

        self.c = Client(api_key="account-xxx", api_secret="xxx", sandbox=True)

    @pyqtSlot()
    def run(self):
        asset = self.argv[0]
        self._flag = True
        try:
            while self._flag:
                # The price of the LAST executed trade on the exchange
                result = list(self.c.get_ticker(asset).values())[3]
                print("result " + result)
                time.sleep(2)
                if not self._flag:
                    break
            else:
                self._flag = False
        except:
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value, traceback.format_exc()))
        else:
            self.signals.result.emit(result) # Return the result of the processing
        finally:
            self.signals.finished.emit() #done

everytime the run_worker function is called (depending on the currentText in the combo box) a new thread is produced.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93

0 Answers0