您可以使用Spring的TaskScheduler实现之一.我提供了一个不需要太多配置的示例(ConcurrentTaskScheduler包装一个单线程的预定执行程序).
The simplest method is the one named schedule that takes a Runnable
and Date only. That will cause the task to run once after the
specified time. All of the other methods are capable of scheduling
tasks to run repeatedly.
简单的工作实例:
private TaskScheduler scheduler;
Runnable exampleRunnable = new Runnable(){
@Override
public void run() {
System.out.println("Works");
}
};
@Async
public void executeTaskT() {
ScheduledExecutorService localExecutor = Executors.newSingleThreadScheduledExecutor();
scheduler = new ConcurrentTaskScheduler(localExecutor);
scheduler.schedule(exampleRunnable,
new Date(1432152000000L));//today at 8 pm UTC - replace it with any timestamp in miliseconds to text
}
...
executeTaskT() //call it somewhere after the spring application has been configured
注意:
To enable support for @Scheduled and @Async annotations add
@EnableScheduling and @EnableAsync to one of your @Configuration
classes
更新 – 取消计划的任务
TaskScheduler的schedule方法返回一个ScheduledFuture,它是一个可以取消的延迟结果的动作.
所以为了取消它,你需要保留一个句柄到计划的任务(即保留ScheduledFuture返回对象).
更改以上代码以取消任务:
>在您的executeTaskT方法之外声明ScheduledFuture.
私人计划
>修改您的调用以调度以保持返回对象:
scheduledFuture = scheduler.schedule(exampleRunnable,
新日期(1432152000000L));
>在您的代码中某个地方的scheduledFuture对象上调用取消
boolean mayInterruptIfRunning = true;scheduledFuture.cancel(mayInterruptIfRunning);