简体   繁体   English

Java 代码应每 5 秒执行一分钟

[英]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.我的要求是我的 java 代码应该每 5 秒执行一次,直到一分钟。 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.我的代码应该在 1 分钟完成后每 5 秒开始运行,它应该停止执行,这意味着我的代码应该执行 12 次并且应该停止。 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...我在这个例子的帮助下尝试了 java util Timer 和 TimerTask ......但它满足了我的要求,它具有每 5 秒执行一次的功能,但它没有在一分钟后终止执行的功能......

Any suggestion will be helpful Thanks You...任何建议都会有所帮助谢谢...

As of Java 1.5, ScheduledExecutorService was introduced and it's preferred to TimerTask.从 Java 1.5 开始,引入了 ScheduledExecutorService 并且它比 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.正如您所看到的 scheduleAtFixedRate 安排您的主要任务以固定速率每 5 秒运行一次。 if you want it to sleep 5 seconds between tasks, try to use scheduleWithFixedDelay.如果您希望它在任务之间休眠 5 秒,请尝试使用 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要在 1.8 之前的 Java 中使用,只需将 lambda 部分()->{...}替换为

new Runnable() {
            @Override
            public void run() {
              ...
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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