98 lines
1.7 KiB
C++
98 lines
1.7 KiB
C++
// TJP COPYRIGHT HEADER
|
|
|
|
//
|
|
// Timer.h
|
|
// algorithm
|
|
//
|
|
// Created by Timothy Prepscius on 1/19/18.
|
|
// Copyright © 2018 Timothy Prepscius. All rights reserved.
|
|
//
|
|
|
|
#pragma once
|
|
|
|
#include "Scheduler.h"
|
|
|
|
#include <core/future/Future.hpp>
|
|
#include <core/future/PromiseOfFutures.hpp>
|
|
|
|
#include <functional>
|
|
#include "Time.h"
|
|
|
|
namespace timprepscius::core::time {
|
|
|
|
template<typename T, typename F>
|
|
Future<T> Scheduler::schedule(Duration period, F &&f)
|
|
{
|
|
Promise<T> v;
|
|
auto event = schedule(
|
|
period,
|
|
false,
|
|
[v, f=std::move(f)]() {
|
|
auto r = v;
|
|
r.consume(f);
|
|
}
|
|
);
|
|
|
|
return v.get_future().then([event](auto &&f) { return f.get(); });
|
|
}
|
|
|
|
|
|
// this should be rewritten to use the above "after", should be much simpler
|
|
|
|
template<typename T, typename F>
|
|
Future<T> Scheduler::schedule_future(Duration period, F &&f_)
|
|
{
|
|
auto v = PromiseOfFutures<T>::generate();
|
|
|
|
auto execute = Promise<void>();
|
|
v->add(
|
|
execute.get_future().then(
|
|
[v_=weak(v), f=std::move(f_)](auto &&) {
|
|
if (auto v = strong(v_))
|
|
{
|
|
v->add(
|
|
f().then(
|
|
[v_](auto &&r) {
|
|
if (auto v = strong(v_))
|
|
v->consume(r);
|
|
}
|
|
)
|
|
);
|
|
}
|
|
}
|
|
)
|
|
);
|
|
|
|
auto event = schedule(
|
|
period,
|
|
false,
|
|
[execute]() {
|
|
auto execute_ = execute;
|
|
execute_.set_value();
|
|
}
|
|
);
|
|
|
|
return v->get_future().then([event](auto &&f) { return f.get(); });
|
|
}
|
|
|
|
|
|
template<typename T, typename F>
|
|
Future<T> Scheduler::schedule(F &&f)
|
|
{
|
|
return schedule<T>(Immediate, std::forward<F>(f));
|
|
}
|
|
|
|
template<typename T, typename F>
|
|
Future<T> Scheduler::schedule_future(F &&f)
|
|
{
|
|
return schedule_future<T>(Immediate, std::forward<F>(f));
|
|
}
|
|
|
|
template<typename F>
|
|
void Scheduler::run(F &&f)
|
|
{
|
|
return schedule<void>(std::forward<F>(f)).wait();
|
|
}
|
|
|
|
} // namespace
|