Skip to content

Commit

Permalink
feat(executor): add execution strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
Serein207 committed Aug 17, 2024
1 parent dad1e6c commit d4a54d4
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions src/Controller/AsyncExecutor.hh
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,18 @@ namespace net = boost::asio; // from <boost/asio.hpp>
template<typename T>
using Task = net::awaitable<T>;

enum class TimerFlag { Once, Periodic };

class AsyncExecutor {
public:
AsyncExecutor(const AsyncExecutor&) = delete;
AsyncExecutor& operator=(const AsyncExecutor&) = delete;

enum TimerFlag {
Immediate = 1,
Delay = 1 << 1,
Once = 1 << 2,
Periodic = 1 << 3,
};

/**
* @brief execute a coroutine and call the callback when it's done
*
Expand Down Expand Up @@ -105,11 +110,18 @@ public:
void asyncExecute(TaskFunc&& func,
CompletionCallback&& callback,
std::chrono::steady_clock::duration interval,
TimerFlag flag = TimerFlag::Periodic) {
asyncExecuteByTimer(std::forward<TaskFunc>(func),
std::forward<CompletionCallback>(callback),
interval,
flag);
int flag = TimerFlag::Periodic | TimerFlag::Immediate) {
assert(!(flag & TimerFlag::Immediate && flag & TimerFlag::Delay));
assert(!(flag & TimerFlag::Periodic && flag & TimerFlag::Once));

if (flag & TimerFlag::Immediate)
asyncExecute(func(), callback);

if (flag & TimerFlag::Periodic || flag & TimerFlag::Delay)
asyncExecuteByTimer(std::forward<TaskFunc>(func),
std::forward<CompletionCallback>(callback),
interval,
flag);
}

net::io_context& getIoContext() { return _ioc; }
Expand Down Expand Up @@ -161,7 +173,7 @@ private:
spdlog::error(ex.what());
}
});
if (flag == TimerFlag::Periodic) {
if (flag & TimerFlag::Periodic) {
asyncExecuteByTimer(std::move(func), std::move(callback), interval, flag);
}
} else {
Expand Down Expand Up @@ -198,7 +210,7 @@ private:
spdlog::error(ex.what());
}
});
if (flag == TimerFlag::Periodic) {
if (flag & TimerFlag::Periodic) {
asyncExecuteByTimer(std::move(func), std::move(callback), interval, flag);
}
} else {
Expand Down

0 comments on commit d4a54d4

Please sign in to comment.