Spring调度任务——只运行一次 [英] Spring scheduling task - run only once
问题描述
是否可以在指定的时间只安排一次 Spring 服务方法?例如,当前时间是下午 2 点,但是当我点击操作按钮时,我希望我的服务方法在晚上 8 点开始.我熟悉@Scheduled 注释,但不确定如何编写不定期运行的 cron 表达式.这个 @Scheduled(cron = "0 0 20 * * ?")
每天晚上 8 点触发.
有什么建议吗?
Is it possible to schedule Spring service method only once at exactly specified time? For example, current time is 2pm but when I hit the action button I want that my service method starts at 8pm. I'm familiar with @Scheduled annotation and I'm not sure how to write cron expression not to run periodically. This one @Scheduled(cron = "0 0 20 * * ?")
fires every day at 8pm.
Any suggestions?
推荐答案
您可以使用 Spring 的 TaskScheduler 实现之一.我在下面提供了一个不需要太多配置的示例(ConcurrentTaskScheduler 包装了一个单线程调度执行器).
You can use one of Spring's TaskScheduler's implementations. I provided an example below with one which does not require too much configuration (ConcurrentTaskScheduler that wraps a single-threaded scheduled executor).
最简单的方法是一个名为 schedule 的方法,它接受一个 Runnable和日期.这将导致任务在之后运行一次指定时间.所有其他方法都能够调度重复运行的任务.
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
注意:
要启用对@Scheduled 和@Async 批注的支持,请添加@EnableScheduling 和 @EnableAsync 到您的 @Configuration 之一班级
To enable support for @Scheduled and @Async annotations add @EnableScheduling and @EnableAsync to one of your @Configuration classes
<小时>
更新 - 取消预定任务
TaskScheduler 的 schedule 方法返回一个 ScheduledFuture,它是一个可以取消的延迟结果操作.
TaskScheduler's schedule method returns a ScheduledFuture which is a delayed result-bearing action that can be cancelled.
所以为了取消它,你需要保留一个计划任务的句柄(即保留 ScheduledFuture 返回对象).
So in order to cancel it, you need to keep a handle to the scheduled task (i.e. keep the ScheduledFuture return object).
更改上面的代码以取消任务:
Changes to the code above for cancelling the task :
- 在 executeTaskT 方法之外声明 ScheduledFuture.
private ScheduledFuture scheduledFuture;
- 修改您对 schedule 的调用以保持返回对象如下:
scheduledFuture = scheduler.schedule(exampleRunnable,
new Date(1432152000000L));
- 对代码中某处的 scheduleFuture 对象调用取消
boolean mayInterruptIfRunning = true;
scheduledFuture.cancel(mayInterruptIfRunning);
这篇关于Spring调度任务——只运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!