Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mlfarrell/926f5f4e0dbf59cf0f10a8f57fda8b4c to your computer and use it in GitHub Desktop.
Save mlfarrell/926f5f4e0dbf59cf0f10a8f57fda8b4c to your computer and use it in GitHub Desktop.
#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;
}
}
#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