/ C++ / 1 min read

Creating a timer in C++

I was recently working on a real-time terminal MMO and I needed timers because Sleep(2000) freezes everything for 2 seconds.

Then I started searching for ways to do this properly and ended up with the following code:

// Usage: timer timer_1(time_in_milliseconds, true_if_async, &function_name, argument_1, arg_2, ...); true makes it multithreaded
class timer
{
public:
    template <class Callable, class... Arguments>
    timer(int after, const bool async, Callable&& f, Arguments&&... args)
    {
        function<typename result_of<Callable(Arguments...)>::type()> task(bind(forward<Callable>(f), forward<Arguments>(args)...));

        if (async)
        {
            thread([after, task]()
			{
                this_thread::sleep_for(chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            this_thread::sleep_for(chrono::milliseconds(after));
            task();
        }
    }
};

Thanks to this, I can create an object from timer class and even set if I want it to work asynchronous or synchronous. If I make it work in synchronous mode, it just acts like Sleep(2000); command. However, if I make it asynchronous program will keep executing itself meanwhile timer object is counting in the background.

Thanks to this, you can actually build timers to work at the same time with your code.

Isn't it cool? I hope it helps you in one of your projects.


Photo by Agê Barros / Unsplash