1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
#include <ctime>
namespace detail
{
template < typename LISTENER, typename... ARGS >
static void do_raise_event( LISTENER listener,
unsigned int initial_delay_ms,
unsigned int period_ms, unsigned int repeat_cnt,
ARGS&&... args )
{
const auto fn = std::bind( listener, std::forward<ARGS>(args)... ) ;
std::this_thread::sleep_for( std::chrono::milliseconds(initial_delay_ms) ) ;
fn() ;
for( unsigned int n = 0 ; n < repeat_cnt ; ++n )
{
std::this_thread::sleep_for( std::chrono::milliseconds(period_ms) ) ;
fn() ;
}
}
}
template < typename LISTENER, typename... ARGS >
void raise_event( LISTENER listener,
unsigned int initial_delay_ms,
unsigned int period_ms, unsigned int repeat_cnt,
ARGS&&... args )
{
std::thread( &detail::do_raise_event<LISTENER,ARGS...>,
listener,
initial_delay_ms,
period_ms, repeat_cnt,
std::forward<ARGS>(args)... ).detach() ;
}
const char* now()
{
const std::time_t now = std::time(nullptr) ;
return std::ctime( std::addressof(now) ) ;
}
void event_handler( int event_id )
{
std::cout << "event #" << event_id << " raised at " << now() << '\n' << std::flush ;
}
int main()
{
std::cout << "trigger event with 3 second delay at " << now() << '\n' << std::flush ;
raise_event( event_handler, 3000, 1000, 2, 999 ) ;
std::this_thread::sleep_for( std::chrono::seconds( 3 + 1*4 ) ) ;
}
|