I have a table in Spring application, that I need to delete expired info after a certain period of time in background. There is a code:
@Service
class HistoryService constructor(
private val historyRepository: HistoryRepository, {
companion object {
fun deleteHistory() {
historyRepository.deleteAll()
}
Starter class
@SpringBootApplication
@EnableScheduling
class Starter {
fun main(args: Array<String>) {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"))
runApplication<Starter>(*args)
val taskService = TaskService
val ses = Executors.newScheduledThreadPool(10)
ses.scheduleAtFixedRate({
taskService.transferTask()
}, 0, 10000, TimeUnit.SECONDS)
}
}
I am not sure that is this a corect way, because in this case there is no transaction annotation in method and in debug I noticed that the application execute this method only one time. How should I change the code to have a service method that will work with database in background?
Your function shouldn't be called main (it's confusing as it looks like the top level main method, but it's within a class which is a Java way of defining main, not a Kotlin way), nor should it have parameters as it's not called from anything other than Spring's scheduling code.
So just have a function inside your configuration class, and annotate it with @Scheduled e.g.
@SpringBootApplication
@EnableScheduling
class Starter {
@Scheduled(fixedDelay = 1000){
fun doIt() {
taskService.transferTask()
}
}