Mariselvam
Mariselvam

Reputation: 4955

how to do Timer task in java

I just want to implement the following in Java , Do anyone have some idea..?

public String method1(){

   //statement1
    .
    .
    .

   //statement 5
}

I want to set a timer for the statemen1 ( which involves some network communication ) . If the statement1 is not getting finished even after 25seconds , the control should go to statement 5 . how can I implement this in java ..?

Upvotes: 3

Views: 2947

Answers (6)

jjnguy
jjnguy

Reputation: 138864

You could do something like this:

private volatile Object resultFromNetworkConnection;    

public String method1(){
   resultFromNetworkConnection = null;
   new Thread(){
       public void run(){
           //statement1
           .
           .
           .
           // assign to result if the connection succeeds
       }
   }.start();
   long start = System.currentMilis();
   while (System.currentMilis() - start < 25 * 1000) {
       if (resultFromNetworkConnection != null) break;
       Thread.sleep(100);
   }
   // If result is not null, you can use it, otherwise, you can ignore it
   //statement 5
}

Upvotes: 1

Dani Cricco
Dani Cricco

Reputation: 8979

Here's is a pattern that you can use. The idea is to start a separate thread to do the network stuff. The "main" thread will wait for the adequate time and check a shared variable that indicates if the networking stuff did his job on time.

public class TestConstrainNetworkOP {

    private Object lock = new Object();
    private Object dataAvailable;

    private Object constrainedNetworkOp() throws InterruptedException {

        Thread t = new Thread(new DoTask());
        t.start();
        Thread.sleep(25000);
        synchronized (lock) {
            if (dataAvailable != null) {
                //the data arrived on time
            }
            else{
                //data is not available and 
                            //maybe throw a timeoutexception
            }
        }
    }

    public class DoTask implements Runnable {

        @Override
        public void run() {
            // do the networking
            synchronized (lock) {
                // save your data here
                dataAvailable = new Long(1);
            }
        }

    }

}

This is a useful pattern if you don't too much control over the network layer (e.g. RMI, EJB). If you are writing the network communication by yourself, then you can set the timeout direct to the socket (as people previously said) or use Java NIO

Upvotes: 0

Koekiebox
Koekiebox

Reputation: 5963

You can make use of the java.util.TimerTask.

extend TimerTask and over-ride the run() method.

What you put in the run method is what should be executed every 25 seconds.

To start the timer do the following:

Timer tmer = new Timer("Network Timer",false);

ExtendedTimerTask extdTT = new ExtendedTimerTask(<params_go_here>) tmer.schedule(extdTT,25000,25000);

You can parse the object which does the networking part at <params_go_here> and assign to a local variable in your ExtendedTimerTask.

When the timer executes you can do the necassary calls on your <params_go_here> object to see if its finished.

Please note that the checker will run in a seperate thread as java.util.TimerTask implements java.util.Runnable

Cool

Upvotes: 3

Peter DeWeese
Peter DeWeese

Reputation: 18333

You mention network communication, so I'll give a rough example with an InputStream from a Socket with a timeout set that may apply to other classes. While you could make timer threads, this is simpler.

socket.setSoTimeout(25 * 1000);

try
{
    data = readMyData(socket.getInputStream());
    doStuff(data);
}
catch(SocketTimeoutException e){ }

doStatement5();

Upvotes: 0

Bozho
Bozho

Reputation: 597016

I/O operations (including network communication) are synchronous. So you can configure a timeout for the particular network communication, and you will have the desired behaviour. How exactly to configure the timeout - depends on what you are using.

Upvotes: 0

aioobe
aioobe

Reputation: 420921

If there is no time-out parameter for the blocking method at statement1, you would have to put statement1 in a separate thread, then wait(25000) for it to finish, if the wait times-out, you go ahead with statement 5 and ignore the result of the blocking call.

Upvotes: 0

Related Questions