I have created a simple scheduled task using Spring Framework\'s @Scheduled annotation.
@Scheduled(fixedRate = 2000)
public void doSomething() {}
>
Another approach that I have not found yet. Simple, clear and thread safe.
In your configuration class add annotation:
@EnableScheduling
This and next step in your class where you need start/stop scheduled task inject:
@Autowired TaskScheduler taskScheduler;
Set fields:
private ScheduledFuture yourTaskState;
private long fixedRate = 1000L;
Create inner class that execute scheduled tasks eg.:
class ScheduledTaskExecutor implements Runnable{
@Override
public void run() {
// task to be executed
}
}
Add start() method:
public void start(){
yourTaskState = taskScheduler.scheduleAtFixedRate(new ScheduledTaskExecutor(), fixedRate);
}
Add stop() method:
public void stop(){
yourTaskState.cancel(false);
}
TaskScheduler provide other common way for scheduling like: cron or delay.
ScheduledFuture provide also isCancelled();