问题描述
是否可以在正好指定的时间只调度一次Spring服务方法?例如,当前时间是2pm,但是当我点击操作按钮,我想我的服务方法在晚上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).
阅读更多
简单的工作范例:
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
请注意:
更新 - 取消预定任务
Update - cancelling the scheduled task
TaskScheduler的计划方法返回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;
Declare the ScheduledFuture outside your executeTaskT method.
private ScheduledFuture scheduledFuture;
修改您的通话以保持返回对象的原样:
scheduledFuture = scheduler.schedule(exampleRunnable,
new Date(1432152000000L));
Modify your call to schedule to keep the return object as such:scheduledFuture = scheduler.schedule(exampleRunnable, new Date(1432152000000L));
在您的代码中某处的scheduledFuture对象上调用cancel
boolean mayInterruptIfRunning = true;
scheduledFuture.cancel(mayInterruptIfRunning);
Call cancel on the scheduledFuture object somewhere in your codeboolean mayInterruptIfRunning = true;scheduledFuture.cancel(mayInterruptIfRunning);
这篇关于Spring调度任务 - 只运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!