我使用 TimerTask
每 3 秒发送消息,但只发送一次。
public static void main(String[] args) throws IOException {
soc = new Socket("localhost", 12345);
out = new PrintWriter(soc.getOutputStream(), true);
send();
}
private static void send() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
out.println("fetewtewwefwfewf egreg \n");
out.flush();
InputStream is;
try {
is = soc.getInputStream();
DataInputStream dis = new DataInputStream(is);
while (!soc.isClosed()) {
long value = dis.readLong();
System.out.println(value);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 3000);
}
}
最佳答案
您正在使用timer.schedule(TimerTask task, long delay)
,它仅安排任务执行一次。对于重复执行,请使用timer.scheduleAtFixedRate(TimerTask任务,长延迟,长周期),即将代码更改为
timer.scheduleAtFixedRate(new TimerTask() {
....
}, 0, 3000);
关于java - 如何为PrintWriter设置TimerTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15518589/