-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer_task_error.cpp
More file actions
42 lines (34 loc) · 999 Bytes
/
Copy pathtimer_task_error.cpp
File metadata and controls
42 lines (34 loc) · 999 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <simple_timer/simple_timer.h>
#include <chrono>
#include <iostream>
#include <stdexcept>
#include <thread>
int64_t get_ms()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
.count();
}
void task_error()
{
static thread_local int num = 1;
int64_t ms = get_ms() % 100000;
std::cout << ms << ": Task executed " << num << " times.\n";
if (num == 11)
{
throw std::runtime_error("Boom! Error occurred in task.");
}
num++;
}
int main()
{
SimpleTimer timer(std::chrono::milliseconds(200)); // 200ms执行一次
// 启动定时器,任务每200ms执行一次
timer.start(task_error);
std::cout << "Timer started, task will execute every 200ms.\n";
// 让定时器跑一段时间,让任务有机会执行多次
std::this_thread::sleep_for(std::chrono::seconds(5)); // 等待5秒钟
// 停止定时器
timer.stop();
std::cout << "Timer stopped after 5 seconds.\n";
return 0;
}