猿问

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


    }


子衿沉夜
浏览 129回答 3
3回答

UYOU

我认为您应该使用 RxJava 和 Job Scheduler 以特定时间间隔安排任务。例如:Observable.interval(50,&nbsp;TimeUnit.SECONDS) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.doOnNext(n&nbsp;->&nbsp;performYourtask()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.subscribe();

蛊毒传说

为什么不安排一次,然后自行取消?long duration=whatever;java.util.Timer timer = new java.util.Timer();&nbsp; &nbsp; &nbsp; &nbsp; java.util.TimerTask task = new java.util.TimerTask() {&nbsp; &nbsp; &nbsp; &nbsp; long t0=System.currentTimeMilis(); // or set it upon scheduling;&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; //this will stop the task from executing in future.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if((System.currentTimeMillis() - t0) >= duration) { this.cancel(); return;}&nbsp; &nbsp; &nbsp; &nbsp; // do actual work&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RemoteKey.send(PageUp);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };timer.scheduleAtFixedRate(task,initialDelay,delayBetweenActions);更现代的方法是使用ScheduledExecutorService.

喵喔喔

这将是最佳方法,使用现代ScheduledExecutor因为时间跨度,比如 50 秒,由获取操作决定,并且该操作是同步的,您只需要等待它结束。// Start the executor, scheduling your Runnable Task to run every 10 secondsexecutorService.scheduleAtFixedRate(&nbsp; &nbsp; &nbsp; &nbsp; () -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Send your data&nbsp; &nbsp; &nbsp; &nbsp; }, 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 overexecutorService.shutdown();Executor可以通过工厂方法创建。Executors.newScheduledThreadPool(5);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // For multiple, concurrent threadsExecutors.newSingleThreadScheduledExecutor(); // For a synchronous "queue"
随时随地看视频慕课网APP

相关分类

Java
我要回答