如何为 java 中的代码添加超时和轮询?

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

这是我的代码:

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);

我每分钟都在轮询此代码

我的问题是如何为此添加超时

例如:每分钟轮询一次,超时为5分钟?如何在上面的代码中暂停 5 分钟?

TimerTask里面,你可以查看已经过了多少时间,然后调用timer.cancel()来停止它。

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);
 }
}