简体   繁体   中英

Timer tasks using java

I have a requirement that, with in a time duration (suppose it is 50 sec, the time might be dynamic) i have to fetch some data from a server. At the same time every 10sec (in between this 30 sec), I have to send some keys to server.

for that iam using below code....but it is not working

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

    }

Why not schedule once, and cancel itself?

long duration=whatever;

java.util.Timer timer = new java.util.Timer();
        java.util.TimerTask task = new java.util.TimerTask() {
        long t0=System.currentTimeMilis(); // or set it upon scheduling;
        @Override
        public void run() {
        //this will stop the task from executing in future.
         if((System.currentTimeMillis() - t0) >= duration) { this.cancel(); return;}
        // do actual work
          RemoteKey.send(PageUp);
        }
        };

timer.scheduleAtFixedRate(task,initialDelay,delayBetweenActions);

More modern approach would be to use ScheduledExecutorService .

I think you should use RxJava and Job Scheduler to schedule the task at particular interval.

For example:

Observable.interval(50, TimeUnit.SECONDS)
                    .doOnNext(n -> performYourtask())
                    .subscribe();

This would be the optimal approach, using the modern ScheduledExecutor
As the timespan of, say 50 seconds, is ruled by the fetching operation, and that operation is synchronous, you'll just have to wait for it to end.

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

The Executor can be created via Factory method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM