2

I just started learn Java and I'm stuck with this problem: I have an infinite while-loop which creates a message to send over a socket; currently the message is not send until a number of elements is poll from a queue and read them.

String msg = null;
String toSend = "";
String currentNumOfMsg = 0;
String MAX_MSG_TO_SEND = 200;
while(true) {
    if ((msg = messageQueue.poll()) != null) { // if there is an element in the list
        toSend += (msg + "#");
        currentNumOfMsg++;

        if (currentNumOfMsg == MAX_MSG_TO_SEND) {
            try {   
                sendMessage(toSend); // send to socket
            } finally {
                msg = null;
                toSend = "";
                currentNumOfMsg = 0;
            }
        }
    }
}

My goal is to send the message after N seconds, without waiting to reach the MAX_MSG_TO_SEND... Is it possible to do it or I shall continue with this approach?

toom501
  • 317
  • 1
  • 3
  • 14

2 Answers2

2

While the other answer is perfectly valid, I thought it may be valuable to tell you that ScheduledExecutorService (documentation found here), lets you call a function foo() every n seconds using the method scheduleAtFixedRate().

Basically, the actually setting up the executor is as easy as:

ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
ses.scheduleAtFixedRate(foo, 0, n, TimeUnit.SECONDS); 

I think putting any more code in here is bit unnecessary, but to see how to do this in more detail, look here, here, or here. These links give some basic examples. I would really recommend doing it this way as this class is part of the java util library (so no extra dependencies) and you don't actually have to worry very much about the multithreading/scheduling part of it, it takes care of all that for you. But thats just my $.02.

Leave a question/comment if you have one, I'll try to answer it.

Alerra
  • 1,239
  • 7
  • 21
1

Yeah, definitely you can do such a thing. But at first you should store your receive messages in a data structure and when you want to send the data via the socket, send the data in the data structure.

also, you can use guava stopWatch to send the message exactly on time. for further information, you can see https://dzone.com/articles/guava-stopwatch

Otherwise, you can use a long variable which stores System.currentTimeMillis() and each time checks if the expected elapsed time is received or not like below sample code:

long l = System.currentTimeMillis();
if(System.currentTimeMillis() - l >= 10000) {
    //send data
}