Event Timer with Configurable Time Interval in C++

In this exercise, you will create an event timer in C++ that allows the user to set a configurable time interval. The timer will repeatedly execute an event after each interval and display a message indicating the event has occurred. This program demonstrates how to manage time intervals, user input, and loops in C++. The timer will wait for the specified amount of time before executing the event again. This is a useful concept for implementing periodic tasks and automation systems.

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

 Copy 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
...

Share this C++ Exercise


More C++ Programming Exercises of Real-Time Programming in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.