Java 如何设置PrintWriter的TimerTask?
我使用Java 如何设置PrintWriter的TimerTask?,java,timertask,Java,Timertask,我使用TimerTask每3秒发送一次消息,但它只发送一次 public static void main(String[] args) throws IOException { soc = new Socket("localhost", 12345); out = new PrintWriter(soc.getOutputStream(), true); send(); } private
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任务,长延迟)
,该任务只调度一次。对于重复调度,您应该使用
timer.schedule(TimerTask任务、长延迟、长周期)
但正如
它不会增加任务执行时间的开销。并将在下次特定的期间执行
而timer.schedule(TimerTask t,long d,long period)
将包括任务的执行时间,并将在上一个任务完成后的时间段执行下一次任务。您使用的是timer.schedule(TimerTask任务,long delay)
只为一次执行计划任务。对于重复执行,请使用timer.scheduleAtFixedRate(TimerTask任务,长延迟,长周期)
,这就是将代码更改为
timer.scheduleAtFixedRate(new TimerTask() {
....
}, 0, 3000);
与timer.scheduleAtFixedRate(TimerTask,长延迟,长周期)相比,timer.scheduleAtFixedRate(TimerTask,长延迟,长周期)有什么区别吗?
是的,timer.scheduleAtFixedRate()是固定延迟。下一个任务的执行在上一个任务完成后以指定的延迟进行调度。例如,如果周期=3秒,任务执行需要1秒,则每4秒执行一次。
timer.scheduleAtFixedRate(new TimerTask() {
....
}, 0, 3000);