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

lskq00tm  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(59)

我在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)
  }
}


我不确定这是一个正确的方式,因为在这种情况下,没有transaction注解在方法和调试我注意到,应用程序执行这个方法只有一次.我应该如何改变代码,有一个服务方法,将与数据库在后台工作?

c6ubokkw

c6ubokkw1#

你的函数不应该被称为main(这很令人困惑,因为它看起来像顶级main方法,但它在一个类中,这是Java定义main的方式,而不是Kotlin的方式),它也不应该有参数,因为它不是从Spring的调度代码之外的任何东西调用的。
因此,只需在配置类中添加一个函数,并使用@Scheduled进行注解即可。

@SpringBootApplication
@EnableScheduling
class Starter  {

   @Scheduled(fixedDelay = 1000){
   fun doIt() {
       taskService.transferTask()
   }
}

字符串

相关问题