Myn m
Myn m

Reputation: 43

How to add timeout and poll for a code in java?

Here is my code:

public class TimerDemo {
    public static void main(String[] args) {

        // creating timer task, timer
        TimerTask tasknew = new TimerTask() {
           
            @Override
            public void run() {
           
                    URL url = null;
                    try {
                        url = new URL("http://universities.hipolabs.com/search?alpha_two_code=CN");
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (ProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }  }
 };
        Timer timer = new Timer();

        // scheduling the task at interval
        timer.schedule(tasknew,0, 60000);

I am polling this code for every minute

My question is how to add timeout for this?

For example: Poll for every minute and timeout is 5 minutes? How to give time out for 5 minutes in above code?

Upvotes: 1

Views: 1733

Answers (1)

Edgar Domingues
Edgar Domingues

Reputation: 990

Inside the TimerTask, you can check how much time has passed and call timer.cancel() to stop it.

public class TimerDemo {
  public static void main(String[] args) {

    final long TIMEOUT = 5*60000; // 5 minutes

    Timer timer = new Timer();

    long startTime = System.currentTimeMillis();

    // creating timer task, timer
    TimerTask tasknew = new TimerTask() {   

      @Override
      public void run() {
    
        // Do some work here
        // ...        

        long elapsed = System.currentTimeMillis() - startTime;
        if (elapsed >= TIMEOUT) {
          timer.cancel();
        }
      }
    };

  // scheduling the task at interval
  timer.schedule(tasknew, 0, 60000);
 }
}

Upvotes: 1

Related Questions