Issue
I am working with sheduler.sheduleWithFixedDelay(????, 5,3, TimeUnit.MINUTES);
. What runnable command should I place here?
It is webserver that sends "hello" response. I want add delay to server answer.
I have modified my code, thank you to matt. Now I have runnable command but have no delay..
void main(...){
SheduledExecutorService sheduler = Executors.newScheduledThreadPool(10);
HttpServer server = HttpServer.create(new InetSocketAddress(8001),5);
server.createContext("/test", (exchange -> {
String respText = "";
String requestText = CFG.getConntent(exchange);
if (requestText.contains("Hello")){
respText = "Hello";
}
else if (requestText.contains("Bye")){
respText = "Bye";
}
exchange.sendResponseHeaders(200, 0);
String textToSend = respText;
sheduler.sheduleWithFixedDelay(()->{
OutputStream output = exchange.getResponseBody();
try{
output.write(textToSend.getBytes(StandardCharsets.UTF_8));
output.flush();
}
catch (Exception e){}
exchange.close();
}, 0,10, TimeUnit.MINUTES);
server.setExecutor(sheduler);
server.start();
}
Solution
If I understand you correctly, then you need to put the delay in your response.
server.createContext("/test", (exchange -> {
String respText = "hello";
String requestText = CFG.getConntent(exchange);
exchange.sendResponseHeaders(200, 0);
sheduler.sheduleWithFixedDelay(()->{
OutputStream output = exchange.getResponseBody();
output.write(resp.Text.getBytes(UTF_8));
output.flush();
exchange.close();
}, 5,3, TimeUnit.MINUTES);
});
This should cause the responds body to finish sending after the delay. I figured it should start the response by sending the '200' ok signal first.
Answered By - matt
Answer Checked By - Terry (JavaFixing Volunteer)