package primer;
import java.io.IOException;
import java.util.Timer;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class SocketTextHandler extends TextWebSocketHandler {
public static int hours = 0;
public static int minutes = 0;
public static int seconds = 0;
public static int elapsedTime = 0;
boolean started = false;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws InterruptedException, IOException {
String clientMessage = message.getPayload();
if (clientMessage.startsWith("start")) {
new Timer().scheduleAtFixedRate(new qtask(), 0, 1000);
try {
Thread.sleep(1000);
session.sendMessage(new TextMessage(hours+":"+minutes+":"+seconds));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} }
package primer;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.TimerTask;
public class qtask extends TimerTask {
private String xtime;
public static int hours = 0;
public static int minutes = 0;
public static int seconds = 0;
public static int elapsedTime = 0;
boolean started = false;
String seconds_string = String.format("%02d", seconds);
String minutes_string = String.format("%02d", minutes);
String hours_string = String.format("%02d", hours);
@Override
public void run() {
elapsedTime=elapsedTime+1000;
hours = (elapsedTime/3600000);
minutes = (elapsedTime/60000)%60;
seconds = (elapsedTime/1000)%60;
}
}
@Component или @Service
@Component
public class Qtask extends TimerTask {
private String xtime;
public int hours = 0;
public int minutes = 0;
public int seconds = 0;
public int elapsedTime = 0;
boolean started = false;
@Override
public void run() {
elapsedTime=elapsedTime+1000;
hours = (elapsedTime/3600000);
minutes = (elapsedTime/60000)%60;
seconds = (elapsedTime/1000)%60
// TODO :: set xtime
xtime = String.valueOf(elapsedTime);
}
public String getXtime() {
return this.xtime;
}
}
@Component
public class SocketTextHandler extends TextWebSocketHandler {
@Autowired
private Qtask qtask;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws InterruptedException, IOException {
String clientMessage = message.getPayload();
if (clientMessage.startsWith("start")) {
new Timer().scheduleAtFixedRate(qtask, 0, 1000);
try {
Thread.sleep(1000);
session.sendMessage(new TextMessage(qtask.getXtime()));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}