您的位置:首页 > 其它

windows客户端开发--实现一个多线程定时器

2017-05-12 11:18 295 查看
go了很久了,但是生活还得继续,工作还得继续,今天跟大家分享一个多线程的定时器。

Windows为我们提供了SetTimer和KillTimer

启动

SetTimer(m_hWnd, TESTWM_SENDDING_EMAIL_TIMER, 500, NULL);

响应

然后响应uMsg == TESTWM_SENDDING_EMAIL_TIMER

销毁

KillTimer(m_hWnd, TESTWM_SENDDING_EMAIL_TIMER);

实现一个多线程定时器

这里用标准C++写的,包括了一些C++11特性。

基本的知识之前的博客都有介绍:

时间库chrono库介绍:

C++11中的便利工具–chrono库(处理日期和时间)

http://blog.csdn.net/wangshubo1989/article/details/50507038

c++11 中线程介绍:

C++ 11特性之std::thread–初识

http://blog.csdn.net/wangshubo1989/article/details/49592517

C++11特性之std::thread–初识二

http://blog.csdn.net/wangshubo1989/article/details/49593429

C++11特性之std::thread–进阶

http://blog.csdn.net/wangshubo1989/article/details/49624575

c++11特性之std::thread–进阶二

http://blog.csdn.net/wangshubo1989/article/details/49624669

言归正传,实现一个多线程定时器:

#ifndef TIMER_H_
#define TIMER_H_

#include <thread>
#include <chrono>

class Timer
{
std::thread th;
bool running = false;

public:
typedef std::chrono::milliseconds Interval;
typedef std::function<void(void)> Timeout;

void start(const Interval &interval,
const Timeout &timeout)
{
running = true;

th = std::thread([=]()
{
while (running == true) {
std::this_thread::sleep_for(interval);
timeout();
}
});

}

void stop()
{
running = false;
if (th.joinable())
{
th.join();
}
}
};

#endif  // TIMER_H_


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐