首页 > 解决方案 > 使用java的定时器任务

问题描述

我有一个要求,在一段时间内(假设是 50 秒,时间可能是动态的)我必须从服务器获取一些数据。同时每 10 秒(在这 30 秒之间),我必须向服务器发送一些密钥。

对于那个 iam 使用下面的代码....但它不工作

 public static void main(String[] args) {
    long startTime = System.currentTimeMillis();
    long duration = (50 * 1000);
    do {


       // RESEt request call code goes here..
       /////
       //////
        System.out.println("Rest request");

        java.util.Timer t = new java.util.Timer();
        java.util.TimerTask task = new java.util.TimerTask() {

        @Override
        public void run() {
        //Sending key every 10 sec
          RemoteKey.send(PageUp);

        }

        };
        t.schedule(task, 0, (10 * 1000));
// This do while loop will execute 50 sec
    } while ((System.currentTimeMillis() - startTime) < duration);

    }

标签: java

解决方案


这将是最佳方法,使用现代ScheduledExecutor
因为时间跨度,比如 50 秒,由获取操作决定,并且该操作是同步的,您只需要等待它结束。

// Start the executor, scheduling your Runnable Task to run every 10 seconds
executorService.scheduleAtFixedRate(
        () -> {
            // Send your data
        }, 0, 10, TimeUnit.SECONDS);

// Fetch data from your Server.
// That's a blocking operation, which, let's say will take 50 seconds

// Stop the Executor as the time is over
executorService.shutdown();

Executor可以通过工厂方法创建。

Executors.newScheduledThreadPool(5);          // For multiple, concurrent threads
Executors.newSingleThreadScheduledExecutor(); // For a synchronous "queue"

推荐阅读