#include "synctimer.h"
#include <QDateTime>
#include <QDebug>
#ifdef Q_OS_WINDOWS
#include <windows.h>
#endif
SyncTimer::SyncTimer(int inter) {
    this->inter = inter;
    connect(this, &QThread::finished, this, &QThread::deleteLater);
}
void SyncTimer::run(){
    qint64 curTime;
    sleep = inter;
    if(sleep <= 0) return;
    #ifdef Q_OS_WINDOWS
    timeBeginPeriod(1);
    #endif
    msleep(sleep);
    qint64 exeTime = QDateTime::currentMSecsSinceEpoch();
    while(inter > 0) {
        inter = 0;
        emit timeout();
        curTime = inter;
        if(curTime<=0) break;
        exeTime += curTime;
        curTime = QDateTime::currentMSecsSinceEpoch();
        sleep = exeTime - curTime;
        if(exeTime > curTime) msleep(sleep);
        else exeTime = curTime;
    }
    #ifdef Q_OS_WINDOWS
    timeEndPeriod(1);
    #endif
}
