3

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?

Alex DaSilva
  • 269
  • 1
  • 3
  • 11

4 Answers4

3

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

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • 2
    My guess is self taught. Probably picked up a video game book and went straight to the chapter about making a multi-player game. – Dave Feb 11 '12 at 05:54
0

spawn the above code in a separate thread and enclose it within a while(true) loop.

prathmesh.kallurkar
  • 5,468
  • 8
  • 39
  • 50
0

The best way is to use a Timer. See Java how to write a timer

Community
  • 1
  • 1
Mikhail
  • 7,749
  • 11
  • 62
  • 136
0

This kind of code is not very useful because it blocks the current thread and also seems to unnecessarily clutter the program logic. It's better to delegate it to a worker thread that executes the send in the background. Also Thread.sleep is known to be inaccurate.

As of the latest Java versions, I think the most elegant way to do it is using ScheduledThreadPoolExecutor:

ScheduledThreadPoolExecutor executor = new ScheduledThraedPoolExecutor(1);
executor.scheduleWithFixedDelay(new Runnable() {
          public void run() {
               getPackets().sendGameMessage("[Server Message]: Remember to vote!");
          }
    }, 0, 3500, TimeUnit.MILLISECONDS);

Also you don't have to worry about that annoying InterruptedException.

Tudor
  • 61,523
  • 12
  • 102
  • 142