
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to create timer using C++11?
Here we will see how to make timer using C++. Here we are creating one class called later. This class has following properties.
- int (milliseconds to wait until to run code)
- bool (If this is true, it returns instantly, and run the code after specified time on another thread)
- The variable arguments (exactly we want to feed to std::bind)
We can change the chrono::milliseconds to nanoseconds or microseconds etc. to change the precision.
Example Code
#include <functional> #include <chrono> #include <future> #include <cstdio> class later { public: template <class callable, class... arguments> later(int after, bool async, callable&& f, arguments&&... args){ std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...)); if (async) { std::thread([after, task]() { std::this_thread::sleep_for(std::chrono::milliseconds(after)); task(); }).detach(); } else { std::this_thread::sleep_for(std::chrono::milliseconds(after)); task(); } } }; void test1(void) { return; } void test2(int a) { printf("result of test 2: %d\n", a); return; } int main() { later later_test1(3000, false, &test1); later later_test2(1000, false, &test2, 75); later later_test3(3000, false, &test2, 101); }
Output
$ g++ test.cpp -lpthread $ ./a.out result of test 2: 75 result of test 2: 101 $
first result after 4 seconds. The second result after three seconds from the first one
- Related Articles
- How to create a timer using tkinter?
- How to create a high resolution timer with C++ and Linux?
- How to create a countdown timer with JavaScript?
- Timer in C++ using system calls
- Python Program to Create a Lap Timer
- How to set a timer in Android using Kotlin?
- Timer in C#
- How to create a Dictionary using C#?
- How to create a Directory using C#?
- C# Program to set the timer to zero
- How to make a countdown timer in Android?
- How to set a countdown timer in javascript?
- How to create a pointer for strings using C language?
- How to create a binary image in OpenCV using C++?
- Making a timer in React JS using reactspring animation

Advertisements