This repository has been archived by the owner on Feb 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththrottledhttp.cpp
51 lines (44 loc) · 1.74 KB
/
throttledhttp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "throttledhttp.h"
ThrottledHttp::ThrottledHttp(Http &http) : http(http), milliseconds(1000) {
elapsedTimer.start();
}
HttpReply *ThrottledHttp::request(const HttpRequest &req) {
return new ThrottledHttpReply(http, req, milliseconds, elapsedTimer);
}
ThrottledHttpReply::ThrottledHttpReply(Http &http,
const HttpRequest &req,
int milliseconds,
QElapsedTimer &elapsedTimer)
: http(http), req(req), milliseconds(milliseconds), elapsedTimer(elapsedTimer), timer(nullptr) {
checkElapsed();
}
void ThrottledHttpReply::checkElapsed() {
/*
static QMutex mutex;
QMutexLocker locker(&mutex);
*/
const qint64 elapsedSinceLastRequest = elapsedTimer.elapsed();
if (elapsedSinceLastRequest < milliseconds) {
if (!timer) {
timer = new QTimer(this);
timer->setSingleShot(true);
timer->setTimerType(Qt::PreciseTimer);
connect(timer, SIGNAL(timeout()), SLOT(checkElapsed()));
}
qDebug() << "Throttling" << req.url
<< QString("%1ms").arg(milliseconds - elapsedSinceLastRequest);
timer->setInterval(milliseconds - elapsedSinceLastRequest);
timer->start();
return;
}
elapsedTimer.start();
doRequest();
}
void ThrottledHttpReply::doRequest() {
QObject *reply = http.request(req);
connect(reply, SIGNAL(data(QByteArray)), SIGNAL(data(QByteArray)));
connect(reply, SIGNAL(error(QString)), SIGNAL(error(QString)));
connect(reply, SIGNAL(finished(HttpReply)), SIGNAL(finished(HttpReply)));
// this will cause the deletion of this object once the request is finished
setParent(reply);
}