删除表中过期的数据(Kotlin)

问题描述 投票:0回答:1

我在Spring应用程序中有一个表,我需要在后台在一段时间后删除过期信息。有代码:

@Service
class HistoryService constructor(
private val historyRepository: HistoryRepository,  {
    companion object {
        fun deleteHistory() {
            historyRepository.deleteAll()
        }

入门班

@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)
  }
}

我不确定这是一种正确的方法,因为在这种情况下,方法中没有事务注释,并且在调试中我注意到应用程序仅执行此方法一次。我应该如何更改代码以获得可以在后台与数据库一起使用的服务方法?

spring database kotlin transactions background-process
1个回答
0
投票

你的函数不应该被称为 main (这很令人困惑,因为它看起来像顶级 main 方法,但它位于一个类中,该类是定义 main 的 Java 方式,而不是 Kotlin 方式),也不应该有参数,因为它不是从 Spring 调度代码以外的任何地方调用。

因此,只需在配置类中添加一个函数,并用 @Scheduled 对其进行注释,例如

@SpringBootApplication
@EnableScheduling
class Starter  {

   @Scheduled(fixedDelay = 1000){
   fun doIt() {
       taskService.transferTask()
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.