Yeap, , . - , Timer , TimerTask , .
. , , .
Runnable ExecuteTask, , .
, Runnables , .
, - 10 , , .
:
Execute task = new ExecuteTask( new Runnable(){
public void run(){
System.out.println("Hi");
}
});
task.start();
, , .
import java.util.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.out;
class ScheduledExecutionDemo {
public static void main( String [] args ) {
List<Runnable> runnables = Arrays.asList( new Runnable[]{
new Runnable(){ public void run(){ out.println("I'm the one");}},
new Runnable(){ public void run(){ out.println("I'm the two");}},
new Runnable(){ public void run(){ out.println("I'm the three");}},
new Runnable(){ public void run(){ out.println("I'm the four");}},
});
for( Runnable run : runnables ) {
new ExecuteTask( run ).start();
}
}
}
class ExecuteTask extends TimerTask {
private final static Map<Timer, Long> upTo = new HashMap<Timer, Long>();
private final static Random random = new Random();
private final Timer owner;
private final Runnable task;
public ExecuteTask( Runnable task ) {
this.owner = new Timer();
this.task = task;
upTo.put( owner, currentTimeMillis() + random.nextInt( 10 ) * 1000 );
}
public void start() {
owner.schedule( this, 0 , 1000 );
}
public void run() {
if( shouldRunAgain() ) {
task.run();
} else {
owner.cancel();
}
}
private boolean shouldRunAgain() {
return ExecuteTask.upTo.get( owner ) > currentTimeMillis();
}
}
, , , .
, , , , .
, .