ListenerSupport<Runnable,?> listeners = ListenerSupport.forType( Runnable.class )
.asynchronous()
.delay( 5, TimeUnit.SECONDS )
.build();
TLongList call_times = TCollections.synchronizedList( new TLongArrayList() );
listeners.add( () -> call_times.add( System.currentTimeMillis() ) );
long call1_time = System.currentTimeMillis();
listeners.dispatch().run(); // Lands at T + 5
ThreadKit.sleep( 2, TimeUnit.SECONDS ); // T + 2
assertEquals( "Expected empty: " + call_times, 0, call_times.size() );
long call2_time = System.currentTimeMillis();
listeners.dispatch().run(); // Lands at T + 7
ThreadKit.sleep( 1, TimeUnit.SECONDS ); // T + 3
assertEquals( "Expected empty: " + call_times, 0, call_times.size() );
long call3_time = System.currentTimeMillis();
listeners.dispatch().run(); // Lands at T + 8
ThreadKit.sleep( 3, TimeUnit.SECONDS ); // T + 6
assertEquals( "Expected one time: " + call_times, 1, call_times.size() );
long call4_time = System.currentTimeMillis();
listeners.dispatch().run(); // Lands at T + 11
ThreadKit.sleep( 4, TimeUnit.SECONDS ); // T + 10
assertEquals( "Expected three times: " + call_times, 3, call_times.size() );
ThreadKit.sleep( 1, TimeUnit.SECONDS );
for( int i = 0; i < 10; i++ ) {
if ( call_times.size() == 4 ) break;
ThreadKit.sleep( 200 );
}
assertEquals( "Expected four times: " + call_times, 4, call_times.size() );
assertTimeRange( call_times.get( 0 ), call1_time + 5000, call1_time + 6000 );
assertTimeRange( call_times.get( 1 ), call2_time + 5000, call2_time + 6000 );
assertTimeRange( call_times.get( 2 ), call3_time + 5000, call3_time + 6000 );
assertTimeRange( call_times.get( 3 ), call4_time + 5000, call4_time + 6000 );
}