🌍 Languages/语言: English | 简体中文
SimpleTimer is a cross-platform, lightweight C++11 timer class designed to run tasks periodically in a background thread. It is suitable for scenarios where scheduled task execution is needed. The class supports pause, resume, interval adjustment, and more, all without relying on any third-party libraries (only the C++11 standard library).
- Cross-platform: Works on multiple platforms (Windows, Linux, macOS) using the C++11 standard library.
- Thread-safe: Built with
std::threadandstd::condition_variable. - Flexible Intervals: Uses
std::chrono::durationfor time intervals, supporting any time unit (minutes, seconds, milliseconds, etc.). - Execution Modes: Supports both one-shot (single execution) and periodic execution modes.
- Control: Provides capabilities to pause, resume, restart, and dynamically modify the interval of the timer.
- Timer Precision: The timer’s precision is dependent on the system clock, typically millisecond precision.
- Automatic Cleanup:
SimpleTimerobjects automatically stop the timer on destruction, ensuring proper resource cleanup even ifstopis not explicitly called. - Minimal Dependencies: No third-party libraries required, except for POSIX systems, where the
pthreadlibrary must be linked.
Copy the simple_timer.h file into your project directory. Then, simply include it in your source code:
#include "simple_timer.h"On POSIX systems, since
std::threadis implemented usingpthread, you'll need to link against thepthreadlibrary (e.g., using-lpthread).
You can create a timer with different constructors to configure the interval and mode of execution:
#include "simple_timer.h"
int main()
{
// Default constructor, with a default interval of 10 seconds
SimpleTimer timer;
// Set timer interval using std::chrono::duration
SimpleTimer timer(std::chrono::seconds(1)); // Executes every 1 second
SimpleTimer timer(std::chrono::seconds(5), true); // One-shot, fires after 5 seconds
// Set interval in milliseconds directly
SimpleTimer timer(1000LL); // Interval: 1000 milliseconds
}Call start with a callable (e.g., lambda) to begin periodic execution in a new thread:
#include "simple_timer.h"
int main()
{
SimpleTimer timer(std::chrono::seconds(1));
timer.start([]() {
std::cout << "Timer task executed!" << std::endl;
});
}You can pause and resume the timer while it’s running:
#include "simple_timer.h"
int main()
{
SimpleTimer timer(std::chrono::seconds(1));
timer.start(task);
timer.pause(); // Pause the timer
timer.resume(); // Resume the timer
}The timer can be configured for one-shot execution, meaning it will only run once.
#include "simple_timer.h"
int main()
{
SimpleTimer timer(std::chrono::seconds(5), true); // One-shot execution: 5-second interval
timer.start(task); // Executes 'task' after 5 seconds, does not repeat
}You can change the timer interval dynamically:
#include "simple_timer.h"
int main()
{
SimpleTimer timer(std::chrono::seconds(1)); // 1-second interval
timer.start(task);
timer.set_interval(std::chrono::seconds(2)); // Set new interval to 2 seconds
}Use stop to stop the timer. It will wait for the current task to finish before stopping (blocking call):
#include "simple_timer.h"
int main()
{
SimpleTimer timer(std::chrono::seconds(1));
timer.start(task);
timer.stop(); // Stop the timer
}Use restart to restart the timer with a new task:
#include "simple_timer.h"
int main()
{
SimpleTimer timer(std::chrono::seconds(1));
timer.start(task);
timer.restart([]() {
std::cout << "Timer restarted and task executed!" << std::endl;
});
}You can query the timer's current status:
#include "simple_timer.h"
int main()
{
SimpleTimer timer(std::chrono::seconds(1));
timer.start(task);
if (timer.is_running()) {
std::cout << "The timer is currently running!" << std::endl;
}
}The SimpleTimer class defines three possible states:
Stopped: The timer is not runningRunning: The timer is currently activePaused: The timer is paused
Use the state() method to check the current state:
#include "simple_timer.h"
int main()
{
SimpleTimer timer(std::chrono::seconds(1));
timer.start(task);
if (timer.state() == SimpleTimer::State::Running) {
std::cout << "Timer is running!" << std::endl;
}
}Here’s a full example demonstrating how to use the SimpleTimer class:
#include "simple_timer.h"
#include <iostream>
int main() {
SimpleTimer timer(std::chrono::seconds(1)); // 1-second interval, periodic task
timer.start([]() {
std::cout << "Timer task executed!" << std::endl;
});
std::this_thread::sleep_for(std::chrono::seconds(5)); // Wait for 5 seconds
timer.pause();
std::cout << "Timer paused..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3)); // Wait 3 seconds
timer.resume();
std::cout << "Timer resumed..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5)); // Wait 5 more seconds
timer.stop();
std::cout << "Timer stopped" << std::endl;
return 0;
}Want to schedule a function with parameters? No problem! Check out more usage examples in the examples folder.
- Timer accuracy depends on the system clock, typically accurate to the millisecond.
- If your task accesses shared resources, consider using proper synchronization within the task callable.
SimpleTimer is released under the MIT License. See LICENSE for details.