-2

My requirement is my java code should execute for every 5 seconds until for one minute. My code should start running every 5 seconds after completion of 1 minute it should stop executing that means my code should execute 12 times and it should stop. I tried with java util Timer and TimerTask with the help of this example... but it dent satisfy my requirement it has the functionality just to execute every 5 seconds but it dosen't have the functionality to terminate execution after one minute...

Any suggestion will be helpful Thanks You...

  • 4
    Show Your attempt. What requirement was not satisfied? – Jacek Cz Dec 04 '16 at 12:38
  • add your code to people help you.... – RohitS Dec 04 '16 at 12:41
  • Possible duplicate of [How to stop a Runnable scheduled for repeated execution after a certain number of executions](http://stackoverflow.com/questions/7269294/how-to-stop-a-runnable-scheduled-for-repeated-execution-after-a-certain-number-o) – Shastick Dec 04 '16 at 12:48

1 Answers1

0

As of Java 1.5, ScheduledExecutorService was introduced and it's preferred to TimerTask. you can implement your requirement with it like this:

ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(2);
    ScheduledFuture<?> schedule = executor.scheduleAtFixedRate(() -> {
        //do what you want
    }, 0, 5, TimeUnit.SECONDS);

    executor.schedule(() -> schedule.cancel(false), 1, TimeUnit.MINUTES);

as you can see scheduleAtFixedRate schedule your main task to run every 5 seconds with a fixed rate. if you want it to sleep 5 seconds between tasks, try to use scheduleWithFixedDelay. the second schedule just runs once after a minute to cancel the previous schedule.

EDIT:

to use in java prior to 1.8 just replace lambda section ()->{...} with

new Runnable() {
            @Override
            public void run() {
              ...
            }
        }
Isa Hekmat
  • 758
  • 1
  • 7
  • 19