tags:

views:

203

answers:

2

I'm implementing the x-modem protocol in Java. If there is a timeout while I'm receiving a packet then I have to send negative acknowledgment. I have to start a timer, and when the time is up then I send a message to the sender requesting file transfer from the begining.

But I'm not getting how to do timers in Java; may I see some sample code? Thank you.

+1  A: 

Here some sample code from what I understood your question:

final Timer t = new Timer();
t.schedule(new TimerTask() {
        /**
         * {@inheritDoc}
         */
        @Override
        public void run() {
            // Do what you want
        }
    }, delay);

 if (gotResponse) t.cancel();

Where delay is the amount of milliseconds you want to wait before the Timer executes it's task.

boutta
+1  A: 

Check out the java.util.concurrent package, specifically the ScheduledThreadPoolExecutor class.

The problem with java.util.Timer is that it schedules one background thread to handle the timed tasks, and your tasks can queue up if the task itself takes a while to run (see here for details)

None of these give any real time guarantees.

This book is really good at explaining the usage of the java.util.concurrent package

A_M