Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Timer Every X Seconds

Tags:

java

repeat

timer

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?

like image 886
Grim Reaper Avatar asked Jul 22 '14 17:07

Grim Reaper


1 Answers

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()

like image 198
Fevly Pallar Avatar answered Sep 21 '22 02:09

Fevly Pallar