Created
June 4, 2019 01:46
-
-
Save mlfarrell/926f5f4e0dbf59cf0f10a8f57fda8b4c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "pch.h" | |
#include "Timer.h" | |
#include "System.h" | |
using namespace std; | |
namespace vui | |
{ | |
Timer::Timer(int milliseconds, bool repeating, std::function<void()> callback) | |
{ | |
cancelled = false; | |
auto t0 = chrono::high_resolution_clock::now(); | |
timerThread = thread([=] { | |
while(!cancelled) | |
{ | |
auto wakeup = t0 + chrono::milliseconds(milliseconds*(timesFired+1)); | |
this_thread::sleep_until(wakeup); | |
if(!cancelled) | |
callback(); | |
if(!repeating) | |
break; | |
timesFired++; | |
} | |
}); | |
} | |
Timer::~Timer() | |
{ | |
cancel(); | |
timerThread.detach(); | |
} | |
void Timer::cancel() | |
{ | |
cancelled = true; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <thread> | |
#include <atomic> | |
#include <functional> | |
namespace vui | |
{ | |
///Portable vui timer class (yayyyyy) | |
///Note this thing won't be the most accurate in the world (yet) on every platform | |
class Timer : public std::enable_shared_from_this<Timer> | |
{ | |
public: | |
typedef std::shared_ptr<Timer> Pointer; | |
typedef std::weak_ptr<Timer> WeakPointer; | |
Timer(int milliseconds, bool repeating, std::function<void()> callback); | |
~Timer(); | |
void cancel(); | |
protected: | |
std::thread timerThread; | |
std::atomic_bool cancelled; | |
int timesFired = 0; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment