LeechCraft 0.6.70-17335-ge406ffdcaf
Modular cross-platform feature rich live environment.
Loading...
Searching...
No Matches
throttle.cpp
Go to the documentation of this file.
1/**********************************************************************
2 * LeechCraft - modular cross-platform feature rich internet client.
3 * Copyright (C) 2006-2014 Georg Rudoy
4 *
5 * Distributed under the Boost Software License, Version 1.0.
6 * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
7 **********************************************************************/
8
9#include "throttle.h"
10#include <QTimer>
11
12namespace LC::Util
13{
14 Throttle::Throttle (std::chrono::milliseconds interval, Qt::TimerType type)
15 : Interval_ { interval }
16 {
17 LastInvocation_.start ();
18
19 Timer_.setTimerType (type);
20 Timer_.setSingleShot (true);
21 Timer_.callOnTimeout ([this]
22 {
23 LastInvocation_.restart ();
24
25 if (Queue_.size () > 1)
26 StartTimer (Interval_);
27 Queue_.takeFirst () ();
28 });
29 }
30
31 std::chrono::milliseconds Throttle::GetInterval () const
32 {
33 return Interval_;
34 }
35
37 {
38 BackoffFactor_ += 2;
39 }
40
42 {
43 const bool allowed = std::chrono::milliseconds { LastInvocation_.elapsed () } >= Interval_ && Queue_.isEmpty ();
44 if (allowed)
45 LastInvocation_.restart ();
46 return allowed;
47 }
48
49 void Throttle::await_suspend (std::coroutine_handle<> handle)
50 {
51 if (Queue_.isEmpty ())
52 StartTimer (Interval_ - std::chrono::milliseconds { LastInvocation_.elapsed () });
53
54 Queue_ << handle;
55 }
56
58 {
59 }
60
61 void Throttle::StartTimer (std::chrono::milliseconds timeout)
62 {
63 BackoffFactor_ = std::max (0, BackoffFactor_ - 1);
64 Timer_.start (timeout * (BackoffFactor_ + 1));
65 }
66}
std::chrono::milliseconds GetInterval() const
Definition throttle.cpp:31
void await_resume() const
Definition throttle.cpp:57
void await_suspend(std::coroutine_handle<>)
Definition throttle.cpp:49
Throttle(std::chrono::milliseconds, Qt::TimerType=Qt::TimerType::CoarseTimer)
Definition throttle.cpp:14