用C++写一个定时器线程,每小时触发一次
时间: 2024-03-08 21:46:54 浏览: 98
可以使用C++11中提供的std::thread和std::chrono库来实现定时器线程。具体实现方法如下:
```cpp
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void timer_thread()
{
while (true)
{
// 等待1小时
this_thread::sleep_for(chrono::hours(1));
// 触发定时器事件
cout << "Timer event triggered." << endl;
}
}
int main()
{
// 创建定时器线程
thread t(timer_thread);
// 等待线程结束
t.join();
return 0;
}
```
上述代码中,timer_thread()函数是定时器线程的函数体,其中使用了this_thread::sleep_for()函数来等待1小时,然后触发定时器事件。在main()函数中,创建了定时器线程t,并等待线程结束。
相关问题
用C++写一个定时器线程,每小时触发一次,创建时间文件夹,文件夹名称年月日时
可以在上面的定时器线程的基础上,加入创建时间文件夹的代码。具体实现方法如下:
```cpp
#include <iostream>
#include <thread>
#include <chrono>
#include <ctime>
#include <string>
#include <sys/stat.h>
using namespace std;
// 获取当前时间,返回格式为年月日时的字符串
string get_current_time()
{
time_t t = time(nullptr);
struct tm *now = localtime(&t);
char buf[80];
strftime(buf, sizeof(buf), "%Y%m%d%H", now);
return buf;
}
void timer_thread()
{
while (true)
{
// 等待1小时
this_thread::sleep_for(chrono::hours(1));
// 获取当前时间
string time_str = get_current_time();
// 创建时间文件夹
string folder_name = time_str + "/";
mkdir(folder_name.c_str(), 0777);
// 输出日志
cout << "Folder " << folder_name << " created." << endl;
}
}
int main()
{
// 创建定时器线程
thread t(timer_thread);
// 等待线程结束
t.join();
return 0;
}
```
上述代码中,get_current_time()函数用于获取当前时间,并返回格式为年月日时的字符串。在timer_thread()函数中,先等待1小时,然后获取当前时间,创建时间文件夹,并输出日志。在main()函数中,创建了定时器线程t,并等待线程结束。
C++添加一个3s定时器,可以if条件触发开启关闭
在C++中,你可以使用`std::this_thread::sleep_for()`函数来自STL库来实现一个简单的3秒定时器。如果你想在满足某个if条件后开启或关闭这个定时器,你需要先创建一个标志变量来控制计时器的状态。这里是一个基本的例子:
```cpp
#include <iostream>
#include <thread>
#include <chrono> // 引入时间库
// 定义一个标志变量
bool timerActive = false;
// 定义一个函数来处理定时器任务
void timerTask() {
while (true) {
if (timerActive) {
std::cout << "Timer is running for 3 seconds." << std::endl;
// 这里可以替换为你的业务逻辑,比如检查条件
std::this_thread::sleep_for(std::chrono::seconds(3)); // 等待3秒
} else {
break; // 如果定时器关闭,则跳出循环
}
}
}
int main() {
std::thread timerThread(timerTask); // 创建一个新线程运行定时器函数
// 开启或关闭定时器
if (/* 条件满足 */) {
timerActive = true; // 设置标志为真,启动定时器
timerThread.detach(); // 将定时器线程设置为守护线程,主线程不会因该线程结束而终止
} else {
timerActive = false; // 关闭定时器
}
return 0;
}
```
在这个例子中,`timerTask()`会在无限循环中等待,直到`timerActive`变为`false`才会停止。你可以通过改变`main()`函数中的if条件来启动或关闭定时器。
阅读全文
相关推荐














