延迟执行代码
delayed execution of code
假设我们在一个函数中,每当按下鼠标按钮时都会调用
static inline LRESULT CALLBACK WndProc(const int code, const WPARAM wParam, const LPARAM lParam){
}
我现在想在5秒钟内没有按下任何按钮后执行一些代码。如果在2秒钟后,用户单击鼠标按钮,则"计时器"应重置并再等待5秒钟。
这甚至可以在C++中完成吗?如果我使用Sleep(5000)
,如果在两者之间按下另一个按钮,我将无法阻止代码运行。
这是我的类(它并不完美,但你可以看看它是如何实现的(,用于控制套接字后面程序的心跳。当beat((方法被调用时,计时器被"重置"。
class HeartbeatController
{
private:
using ms = std::chrono::milliseconds;
public:
HeartbeatController(std::function<void()> &heartbeatLostCallback,
const ms &panicTime = ms{5000}, //time in milliseconds, after which panic code will be executed
const ms &checkDuration = ms{ 1000 }) noexcept :
heartbeatLostCallback{ heartbeatLostCallback }
{}
~HeartbeatController() = default;
HeartbeatController(HeartbeatController &&other) :
heartbeatLostCallback{ std::move(other.heartbeatLostCallback) },
loopThread{ std::move(other.loopThread) },
lastBeat{ std::move(other.lastBeat) },
panicTime{ std::move(other.panicTime) },
checkDuration{ std::move(other.checkDuration) }
{}
HeartbeatController& operator=(HeartbeatController &&other)
{
heartbeatLostCallback = std::move(other.heartbeatLostCallback);
loopThread = std::move(other.loopThread);
lastBeat = std::move(other.lastBeat);
panicTime = std::move(other.panicTime);
checkDuration = std::move(other.checkDuration);
return *this;
}
HeartbeatController(const HeartbeatController&) = delete;
HeartbeatController& operator=(const HeartbeatController&) = delete;
void interrupt() noexcept
{
interrupted = true;
}
void beat() noexcept
{
lastBeat = Clock::now();
}
void start()
{
auto loop = [this]
{
while (!interrupted)
{
if (Clock::now() - lastBeat > panicTime)
heartbeatLostCallback(); //here you can insert some your code which you wanna execute after no beat() for panicTime duration
std::this_thread::sleep_for(checkDuration);
}
};
lastBeat = Clock::now();
loopThread = std::thread{ loop };
}
private:
using Clock = std::chrono::system_clock;
std::reference_wrapper<std::function<void()>> heartbeatLostCallback;
std::thread loopThread;
std::chrono::time_point<Clock> lastBeat;
std::chrono::milliseconds panicTime;
std::chrono::milliseconds checkDuration;
bool interrupted = false;
};
相关文章:
- 以下代码执行哪种内存分配(动态或静态)?
- 允许多个互斥锁所有者或指定数量的并发代码执行
- 使用 execv 从C++代码执行的 Linux 脚本失败
- 由于找不到cpprest_2_10.dll,代码执行无法继续
- 在每次循环迭代时停止代码执行毫秒
- 与Java相比,为什么此C 代码执行速度如此慢
- 记录组件代码执行
- 相同的代码执行两次:性能差异
- 代码执行/CPU 速度每 2 秒减慢一次
- 函数返回本地变量,尽管变量不超出范围,没有编译器问题,并且代码执行
- 如何将字符串从C++DLL返回到MetaTrader 4代码执行生态系统?
- 当我从java代码执行C++时不显示任何输出
- C++和共享库中的代码执行点
- 递归期间代码执行中断
- 为可选的评测代码执行进行高效设计
- 我正在尝试使用 ifstream 将此 C 函数的等效代码执行到 c++ 中
- 最佳C 11测量嵌入式系统代码执行时间的方法
- 如何在iOS应用程序中锁定代码执行
- 中断代码执行
- 是否有一个工具来记录代码执行