Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何设置PrintWriter的TimerTask?_Java_Timertask - Fatal编程技术网

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);