Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I make a thread loop?

Every 3 seconds, I want the server to send a message. To do this, I have this code.

    try {
        Thread.sleep(3500);
        getPackets().sendGameMessage("[Server Message]: Remember to vote!");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

The code works of course, waits 3 and a half seconds, sends the message. But how can I make it loop, so every 3 and a half seconds, it will send it without stopping?

like image 225
Alex DaSilva Avatar asked Feb 02 '26 06:02

Alex DaSilva


1 Answers

I'm a bit surprised that someone tackling networking in Java doesn't know how to put code in an infinite loop. Thus, I wonder if your real question is "is there a better way?"

To that question, I would say that you should consider using either java.util.Timer to send the message, or using scheduleAtFixedRate() from a ScheduledExecutorService obtained from Executors.newScheduledThreadPool().

like image 193
Mark Peters Avatar answered Feb 03 '26 19:02

Mark Peters