Hi, I have some small problem. I need to write some function in C++ witch should call some other function each next seconds. Is there any built in function for that in C++ ?
#include <iostream>
#include <thread>
#include <chrono>
#include <functional>
#include <ctime>
void periodic_call( int period_in_milliseconds, int ntimes, std::function< void() > function )
{
constauto period = std::chrono::milliseconds(period_in_milliseconds) ;
std::chrono::milliseconds delta{} ;
for( int i = 0 ; i < ntimes ; ++i )
{
std::this_thread::sleep_for( period - delta ) ;
// assumes that the time taken to execute the function is less than period_in_milliseconds
auto start = std::chrono::steady_clock::now() ;
function() ;
auto end = std::chrono::steady_clock::now() ;
delta = std::chrono::duration_cast<std::chrono::milliseconds>(end-start) ;
}
}
void foo( int a, int b )
{
staticint n = 0 ;
staticint c = 0 ;
c = c*a + b ;
auto t = std::time(nullptr) ;
char now[128] ;
std::strftime( now, sizeof(now), " at %T\n", std::localtime(&t) ) ;
std::cout << ++n << ". " << "foo::c == " << c << now << std::flush ;
}
int main()
{
// launch a thread to call foo(2,3) once every 2 seconds, 5 times in all
std::thread( periodic_call, 2000, 5, std::bind( foo, 2, 3 ) ).join() ;
}
@ OP: The short answer is no. JLBorges solution would do what you are asking. I don't know why it was reported, it isn't a thread bomb or anything malicious since the number of executions is managed by the for loop. He could use some more documentation but that is certainly no reason to report him. What do you mean by "next seconds" by the way? Does the interval between the executions change?
P.S.: This kind of thing is better managed by the task scheduler on the OS.