Scheduled services are usually used to implement batch processing that can run simultaneously with the request handlers. To create these types of services, follow these steps:
- To enable schedule-based transactions, create a context definition SpringScheduledConfig which implements org.springframework.scheduling.annotation.SchedulingConfigurer. Apply the class-level annotation @EnableScheduling and override the method configureTasks() with the preferred configurations of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler injected in it:
@Configuration @EnableScheduling public class SpringScheduledConfig implements SchedulingConfigurer { @Bean() public ThreadPoolTaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(100); scheduler.setThreadNamePrefix("Scheduler-"); scheduler.setWaitForTasksToCompleteOnShutdown(true); scheduler.setRemoveOnCancelPolicy(true); return scheduler; } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setTaskScheduler(taskScheduler()); } }
- Now, create a service class TimeService which contains the following template methods:
public interface TimedService { public void batchFixedPeriod(); public void batchCronPeriod(); public void batchFixedDelay(); public void batchInitialDelay(); }
- Then, create an implementation class that will implement a time-triggered process that runs every 2000 milliseconds everyday on a separate thread generated by ThreadPoolTaskScheduler from its pool of threads:
@Service public class TimedServiceImpl implements TimedService{ @Scheduled(fixedRate=2000) @Override public void batchFixedPeriod() { System.out.println("scheduled#batchFixedPeriod: " + Thread.currentThread().getName()); } }
- Add another scheduled process that uses a cron expression which defines its execution every five seconds daily:
@Scheduled(cron="*/5 * * * * ?") @Override public void batchCronPeriod() { System.out.println("scheduled#batchCronPeriod: " + Thread.currentThread().getName()); }
- Create a @Scheduled process that runs for a fixed period of 5000 milliseconds, given that at the start of the execution, it incurs an initial delay of 2000 milliseconds:
@Scheduled(fixedRate=5000, initialDelay=2000) @Override public void batchInitialDelay() { System.out.println("scheduled#batchFixedDelay: " + Thread.currentThread().getName()); }
- Lastly, implement a batch process that executes every 5000 milliseconds with a delay of 1000 millisecond every after completion per execution:
@Scheduled(fixedDelay=1000) @Override public void batchFixedDelay() { System.out.println("scheduled#batchFixedDelay: " + Thread.currentThread().getName()); }