Group
Real-Time Programming in C++
Objective
Write a C++ program that takes an interval time in seconds from the user, and after each interval, it executes an event (display a message). The timer should continue to run until the user stops it. Make sure to implement a loop that waits for the specified time interval before executing the event again.
Create an event timer with a configurable time interval.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the input-output stream library
#include <thread> // Include the thread library to implement delays
#include <chrono> // Include the chrono library for time-related functions
using namespace std;
// Function to implement the event timer
void eventTimer(int interval) {
while (true) { // Run the timer indefinitely (until the user stops it)
// Display the event message
cout << "Event triggered! Interval: " << interval << " seconds" << endl;
// Wait for the specified interval before triggering the next event
this_thread::sleep_for(chrono::seconds(interval));
}
}
int main() {
int interval;
cout << "Enter the time interval in seconds for the event: ";
cin >> interval; // Input the interval time in seconds
// Call the eventTimer function with the input interval
eventTimer(interval);
return 0;
}
Output
Enter the time interval in seconds for the event: 3
Event triggered! Interval: 3 seconds
Event triggered! Interval: 3 seconds
Event triggered! Interval: 3 seconds
...