Click here to Skip to main content
14,929,833 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have Timer class in c++,but I am not getting as expected output.

C++
#include <iostream>
#include <chrono>
#include <thread>#include <functional>
using namespace std;

class Timer {
    bool clear = false;

public:
    void setTimeout(auto function, int delay);
    void setInterval(auto function, int interval);
    void stop();
};


void Timer::setTimeout(auto function, int delay) {
    std::cout<<"Inside setTimeout"<<std::endl;
 this-="">clear = false;
    std::thread t([=]() {
        if(this->clear) return;
        std::this_thread::sleep_for(std::chrono::milliseconds(delay));
        if(this->clear) return;
        function();
    });
    t.detach();
}

void Timer::setInterval(auto function, int interval) {
    std::cout<<"Inside setInterval"<<std::endl;
 this-="">clear = false;
    std::thread t([=]() {
        while(true) {
            if(this->clear) return;
             std::cout<<"Going to sleep"<<std::endl;
 std::this_thread::sleep_for(std::chrono::milliseconds(interval));
="" if(this-="">clear) return;
            function();
        }
    });
    t.detach();
}


void Timer::stop() {
    this->clear = true;
}

int main()
{
    Timer t = Timer();

       t.setInterval([&]() {
        cout << "Hey.. After each 1s..." << endl;//not printing
         }, 1000); 

        t.setTimeout([&]() {
         cout << "Hey.. After 5.2s. But I will stop the timer!" << endl;//not printing
        t.stop();
        }, 5200);

    return 0;
}


What I have tried:

I have executed the timer class, but not getting the output.
Posted
Updated 24-Apr-21 3:44am
v2
Comments
Richard MacCutchan 24-Apr-21 8:38am
   
What output? Please explain your problem in full detail.

1 solution

The problem is that your main method sets up the timers and immediately terminates, at which point your Timer object get destroyed. I added the following code just before the return statement in main, to delay that:
C++
while (!t.clear)
{
    std::this_thread::sleep_for (std::chrono::milliseconds(500));
}
   
Comments
Member 15025528 24-Apr-21 10:29am
   
Thanks Richard
It's working.
Richard MacCutchan 24-Apr-21 12:04pm
   
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900