[英]Use ScheduledExecutorService to run code at specific Date time only once
我有一个必须在将来某个日期时间执行的代码,比方说,我有一个将来的日期,我想在将来的该日期+1分钟执行一次和平的代码, 但只能执行一次 。 我知道我使用Java Timer和TimerTask来执行此操作,例如执行以下操作:
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Calendar myDate = Calendar.getInstance();
myDate.add(Calendar.MINUTE, 1);
Date afterOneMinute = myDate.getTime();
System.out.println("Scheduled at:" + afterOneMinute);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Executed at:" + (new Date()));
}
}, afterOneMinute);
}
}
我正在寻找一种使用ScheduledExecutorService达到同一目的的优雅方法,以便拥有一个特定的池,因为该池将用于多个调用。 有人可以帮我吗?
您可以使用ScheduledExecutorService.schedule(Runnable command, long delay, TimeUnit unit)
long delay = afterOneMinute.getTime() - System.currentTimeMillis();
ScheduledExecutorService executorService = ...;
executorService.schedule(runnable, delay, TimeUnit.MILLISECONDS);
您可以从Executors
获取ScheduledExecutorService
,获取SingleThread
版本或MultipleThread
Executors.newSingleThreadScheduledExecutor
然后提供runnable
, duration
及其TimeUnit
: ScheduledExecutorService.schedule(Runnable command, long delay, TimeUnit unit)
如果要设置持续时间:
ScheduledExecutorService exe = Executors.newSingleThreadScheduledExecutor();
// or Executors.newScheduledThreadPool(2); if you have multiple tasks
exe.schedule(() -> System.out.println("Executed at:" + (new Date())), 1, TimeUnit.MINUTES);
如果要使用LocalDateTime
:
ScheduledExecutorService exe = Executors.newSingleThreadScheduledExecutor();
// or Executors.newScheduledThreadPool(2); if you have multiple tasks
LocalDateTime date = LocalDateTime.of(2018, 6, 17, 18, 30, 0);
exe.schedule(
() -> System.out.println("Executed at:" + (new Date())),
LocalDateTime.now().until(date, ChronoUnit.MINUTES),
TimeUnit.MINUTES);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.