Spring Scheduler
A Spring wrapper of Java Scheduler. To use scheduler, we have to @EnableScheduling
in application class:
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And then, if we're using Virtual Thread from JDK 21, we can enable spring.threads.virtual.enabled=true
If doing so, we will then have an autowired version of SimpleAsyncTaskScheduler
If it's not JDK 21, we will then have ThreadPoolTaskScheduler
instead.
To schedule a task, we can just do
@RestController
@RequiredArgsConstructor
public class MyController {
private final ThreadPoolTaskScheduler threadPoolTaskScheduler;
@RequestMapping(value = "/schedule", method = RequestMethod.POST)
public String scheduleTask(@RequestBody Task task) {
simpleAsyncTaskScheduler.scheduleAtFixedRate(() -> taskService.run(task), Instant.now(), Duration.ofSeconds(1));
return String.format("Scheduled %s", task);
}
}
OR we can just call @Scheduled
@Slf4j
@Service
public class TaskService {
@Scheduled(fixedDelay = '1')
public void run() {
log.debug("Performing task {}", task);
}
}