Reputation: 561
So, I basically need a command to run every 5 seconds, but the Timer doesn't work... I tried so many different methods, The only thing that works is the Thread.sleep(Milliseconds); But that causes my whole game to stop working... If I try using a timer, for example:
Timer timer = new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hey");
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
How can I get this timer to fire correctly?
Upvotes: 9
Views: 17621
Reputation: 3099
You should pair java.util.Timer
with java.util.TimerTask
Timer t = new Timer( );
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("Hey");
}
}, 1000,5000);
1000 means 1 second delay
before get executed
& 5000 means will be repeated every 5 seconds
.
To stop it , simply call t.cancel()
Upvotes: 13