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 servic
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).
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.
Read more on task execution & scheduling
Simple working example:
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
Note:
To enable support for @Scheduled and @Async annotations add @EnableScheduling and @EnableAsync to one of your @Configuration classes
Update - cancelling the scheduled task
TaskScheduler's schedule method returns a ScheduledFuture which is a delayed result-bearing action that can be cancelled.
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 :
private ScheduledFuture scheduledFuture;
scheduledFuture = scheduler.schedule(exampleRunnable,
new Date(1432152000000L));
boolean mayInterruptIfRunning = true;
scheduledFuture.cancel(mayInterruptIfRunning);
The title of the question implies a one-shot task runner is required. Here is a task class that will run once after a delay (or replace with an epoch as the OP requests). Additionally, you can enable/disable it in the application.properties/yaml or with profiles.
@Slf4j
@Component
@ConditionalOnProperty({ "app.scheduler.onceRunner" })
public class RunOnceTask
{
public static final long INITIAL_DELAY_SECS = 5L; // As you wish
@Autowired
@Qualifier("mainTaskScheduler") // You could set a custom TPTS to set threads, name, etc.
private ThreadPoolTaskScheduler poolTaskScheduler;
@PostConstruct
public void run()
{
poolTaskScheduler.scheduleWithFixedDelay( () -> {
log.info( "Once-runner ran once" );
}, new Date( System.currentTimeMillis() + (INITIAL_DELAY_SECS * 1000) ), Long.MAX_VALUE ); // Run once
}
}
In order to not create ScheduledExecutorService
and ConcurrentTaskScheduler
at every method call it is convenient to initialize TaskScheduler
at service creation, e.g.
private final TaskScheduler taskScheduler =
new ConcurrentTaskScheduler(Executors.newScheduledThreadPool(10));
@Async
has no sense as we just schedule task and exit from method.
You can extend PeriodicTrigger as follows - it checks the lastCompletionTime: it will be null if the task has never run before. You can try variation of this if you want to run the task just once at some given time.
class RunOnceTrigger extends PeriodicTrigger {
public RunOnceTrigger(long period) {
super(period);
setInitialDelay(period);
}
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
if(triggerContext.lastCompletionTime() == null) { // hasn't executed yet
return super.nextExecutionTime(triggerContext);
}
return null;
}
}
Dead man's solution:
@Scheduled(initialDelay = 1000 * 30, fixedDelay=Long.MAX_VALUE)
You will be dead before it fires again.