user3201343
user3201343

Reputation: 157

How to create a timer which can be used multiple times in Java

I want to run a timer for multiple requests. If I get a request I will be running the timer for 1000ms in between if I get another request I need to update the timer. If I didn't get any request for 1000ms I need to exit the process.

How to implement such a timer? I can't perform the operation with Timer task.

Upvotes: 0

Views: 853

Answers (1)

cosmin.danisor
cosmin.danisor

Reputation: 963

You can use ScheduledExecutorService

Sample bellow:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class A {

public static void main(String[] args) {
    Runnable  terminate = new Runnable() {
        @Override
        public void run() {
            System.out.println("Terminate task executed");
        }
    };
    ScheduledExecutorService  timer = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<?> futureTask = timer.schedule(terminate, 1, TimeUnit.SECONDS);
    futureTask.cancel(true);
    System.out.println("Timer Canceled");
    futureTask = timer.schedule(terminate, 1, TimeUnit.SECONDS);
    futureTask.cancel(true);
    System.out.println("Timer Canceled");
  }

}

If you run it, you will see terminate task is never run because it is canceled before the 1 SEC passes

Upvotes: 1

Related Questions