swift
threadedtimer.cpp
1 // SPDX-FileCopyrightText: Copyright (C) 2025 swift Project Community / Contributors
2 // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3 
4 #include "misc/threadedtimer.h"
5 
6 #include <QPointer>
7 
8 #include "threadutils.h"
9 
10 namespace swift::misc
11 {
12  CThreadedTimer::CThreadedTimer(QObject *owner, const QString &name, bool singleShot) : QObject(owner)
13  {
14  m_updateTimer.setObjectName(name + ":timer");
15  m_updateTimer.setSingleShot(singleShot);
16  connect(&m_updateTimer, &QTimer::timeout, this, &CThreadedTimer::timeout);
17  }
18 
19  void CThreadedTimer::startTimer(std::chrono::milliseconds ms)
20  {
21  if (!CThreadUtils::isInThisThread(this))
22  {
23  // shift in correct thread
24  QPointer<CThreadedTimer> myself(this);
25  QTimer::singleShot(0, this, [=] {
26  if (!myself) { return; }
27  this->startTimer(ms);
28  });
29  return;
30  }
31 
32  connect(thread(), &QThread::finished, &m_updateTimer, &QTimer::stop, Qt::UniqueConnection);
33  m_updateTimer.start(ms);
34  }
35 
36  void CThreadedTimer::stopTimer()
37  {
38  if (!CThreadUtils::isInThisThread(this))
39  {
40  // shift in correct thread
41  QPointer<CThreadedTimer> myself(this);
42  QTimer::singleShot(0, this, [=] {
43  if (!myself) { return; }
44  this->stopTimer();
45  });
46  return;
47  }
48 
49  if (!m_updateTimer.isActive()) { return; }
50  m_updateTimer.stop();
51  }
52 } // namespace swift::misc
Free functions in swift::misc.
auto singleShot(int msec, QObject *target, F &&task)
Starts a single-shot timer which will call a task in the thread of the given object when it times out...
Definition: threadutils.h:30