How to schedule a periodic task in Java?

前端 未结 11 1835
星月不相逢
星月不相逢 2020-11-22 08:51

I need to schedule a task to run in at fixed interval of time. How can I do this with support of long intervals (for example on each 8 hours)?

I\'m currently using <

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 09:15

    I use Spring Framework's feature. (spring-context jar or maven dependency).

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    
    @Component
    public class ScheduledTaskRunner {
    
        @Autowired
        @Qualifier("TempFilesCleanerExecution")
        private ScheduledTask tempDataCleanerExecution;
    
        @Scheduled(fixedDelay = TempFilesCleanerExecution.INTERVAL_TO_RUN_TMP_CLEAN_MS /* 1000 */)
        public void performCleanTempData() {
            tempDataCleanerExecution.execute();
        }
    
    }
    

    ScheduledTask is my own interface with my custom method execute, which I call as my scheduled task.

提交回复
热议问题