In Java 5+ with a ScheduledExecutorService
:
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// do stuff
}
}, 0, 5, TimeUnit.SECONDS);
The above method is favoured. Prior to Java 5 you used Timer
and TimerTask
:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// do staff
}
}, 0, 5000);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…