简体   繁体   English

如何为PrintWriter设置TimerTask?

[英]how set TimerTask for PrintWriter?

I am using TimerTask to send messages every 3 seconds, but its sending only one time. 我正在使用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);
        }
    }

You are using timer.schedule(TimerTask task, long delay) which schedules the task only for one execution. 您正在使用timer.schedule(TimerTask task, long delay) ,仅将任务安排一次执行。 For repeated executions use timer.scheduleAtFixedRate(TimerTask task, long delay, long period) , that is change you code as 对于重复执行,请使用timer.scheduleAtFixedRate(TimerTask task, long delay, long period) ,即将您的代码更改为

 timer.scheduleAtFixedRate(new TimerTask() {
     ....
 }, 0, 3000);

You should probably look at this link 您可能应该看一下此链接

You are using timer.schedule(TimerTask task, long delay) which is getting scheduled once. 您正在使用要调度一次的timer.schedule(TimerTask task, long delay)
For repeated scheduling you should use timer.schedule(TimerTask task, long delay, long period) 对于重复的调度,您应该使用timer.schedule(TimerTask task, long delay, long period)

But as answered by Evgeniy Dorofeev 但正如叶夫根尼·多罗费耶夫Evgeniy Dorofeev)的回答

timer.scheduleAtFixedRate(new TimerTask(){}, 0, 3000);

it does not have an overhead of execution time of your task. 它没有任务执行时间的开销。 And will be executed next time at specific period . 并且将在特定period下一次执行。
While timer.schedule(TimerTask t, long d, long period) will include the time of execution of your task, and will be executed next time at the period after completion of your previous task. timer.schedule(TimerTask t, long d, long period)将包括您任务的执行时间,并且将在上一个任务完成后的时间period下一次执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM