简体   繁体   中英

Java code should execute every 5 seconds for one minute

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...

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() {
              ...
            }
        }

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