How to make a timer task in java

I just want to implement the following in Java: "Does anyone have an idea?"

public String method1(){

   //statement1
    .
    .
    .

   //statement 5
}

I want to set a timer for statemen1 (which is related to some network connection). If assertion1 does not complete even after 25 seconds, the control should go to statement 5. how can I implement this in java ..?

+3
source share
6 answers

You can use java.util.TimerTask.

pull TimerTaskand drag method run().

What you put in the start method should execute every 25 seconds.

To start the timer, follow these steps:

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

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

, , <params_go_here> ExtendedTimerTask.

, <params_go_here>, , .

, checker , java.util.TimerTask java.util.Runnable

+2

- :

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
}
+1

- block1, 1 , wait(25000) , wait 5 .

0

- ( ) . , - , . - , .

0

, InputStream Socket -, . , .

socket.setSoTimeout(25 * 1000);

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

doStatement5();
0

, . , , . "" , , .

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 template if you do not have too much control over the network layer (for example, RMI, EJB). If you write a network connection yourself, you can set the timeout directly to the socket (as mentioned earlier) or use Java NIO

0
source

Source: https://habr.com/ru/post/1762663/


All Articles