我有一个代码必须在将来某个日期时间执行,假设我有一个未来的日期,我希望在该日期执行代码的和平+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 ,以便拥有一个特定的池,因为这个池将用于多个调用。 有人可以帮助我吗?
答案 0 :(得分:1)
您可以使用this
id = rep(2:6, each = 6)
答案 1 :(得分:1)
您可以从ScheduledExecutorService
获得Executors
,获得SingleThread
版本或MultipleThread
here
然后提供runnable
,duration
及其TimeUnit
:Executors.newSingleThreadScheduledExecutor
如果您想设置持续时间:
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);