0

I am using TimerTask to send messages every 3 seconds, but its sending only one time.

 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);
        }
    }
Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
Max Usanin
  • 2,479
  • 6
  • 40
  • 70

2 Answers2

1

You are using timer.schedule(TimerTask task, long delay) which schedules the task only for one execution. For repeated executions use timer.scheduleAtFixedRate(TimerTask task, long delay, long period), that is change you code as

 timer.scheduleAtFixedRate(new TimerTask() {
     ....
 }, 0, 3000);
Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • is there any difference b/w `timer.scheduleAtFixedRate(TimerTask task, long delay, long period)` and `timer.schedule(TimerTask task, long delay, long period)` – Mohammad Faisal Mar 20 '13 at 09:18
  • 1
    yes, timer.schedule() is fixed-delay. Next task execution is scheduled with a specified delay after the previous task finished. Eg if period = 3 sec and the task execution takes 1 sec then it will be executed every 4 secs. – Evgeniy Dorofeev Mar 20 '13 at 09:26
0

You should probably look at this link

You are using timer.schedule(TimerTask task, long delay) which is getting scheduled once.
For repeated scheduling you should use timer.schedule(TimerTask task, long delay, long period)

But as answered by 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.
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.

Community
  • 1
  • 1
Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117