我正在使用TimerTask
每3秒發送一次消息,但它只發送一次。如何爲PrintWriter設置TimerTask?
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);
}
}
有什麼不同的B/W'timer.scheduleAtFixedRate(TimerTask的任務,長時間的延遲,週期長)'和'timer.schedule(TimerTask的任務,長延遲,長週期)' – 2013-03-20 09:18:34
是的,timer.schedule()是固定延遲。在上一個任務完成後,下一個任務的執行將按照指定的延遲進行。例如,如果週期= 3秒,任務執行需要1秒,那麼它將每4秒執行一次。 – 2013-03-20 09:26:42