ScheduledExecutorService在给定的时间段内以给定的时间执行任务

如何使ScheduledExecutorService在给定的时间段内以给定的时间执行任务?

然后下面的代码将使其以1s的速率执行...但是如何限制所有这些重复的总时间

service.scheduleWithFixedDelay(new Runnable() { ... }, 0, 1, TimeUnit.SECONDS);


慕码人2483693
浏览 244回答 1
1回答

萧十郎

您可以提供另一个Runnable来取消此任务。例子:public static void main(String[] args) {&nbsp; &nbsp; ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);&nbsp; &nbsp; CountDownClock clock1 = new CountDownClock("A");&nbsp; &nbsp; Future<?> f1 = scheduler.scheduleWithFixedDelay(clock1, 3, 10, TimeUnit.SECONDS);&nbsp; &nbsp; Runnable cancelTask = new Runnable() {&nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f1.cancel(true);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; scheduler.schedule(cancelTask, 120, TimeUnit.SECONDS);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java