package com.zooper.demo; import java.text.SimpleDateFormat; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); /** * 每隔5秒執行一次 */ @Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); } /** * 根據cron表達式格式觸發定時任務 * cron表達式格式: * 1.Seconds Minutes Hours DayofMonth Month DayofWeek Year * 2.Seconds Minutes Hours DayofMonth Month DayofWeek * 順序: * 秒(0~59) * 分鍾(0~59) * 小時(0~23) * 天(月)(0~31,但是你需要考慮你月的天數) * 月(0~11) * 天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT) * 年份(1970-2099) * * 注:其中每個元素可以是一個值(如6),一個連續區間(9-12),一個間隔時間(8-18/4)(/表示每隔4小時),一個列表(1,3,5),通配符。 * 由於"月份中的日期"和"星期中的日期"這兩個元素互斥的,必須要對其中一個設置?. */ @Scheduled(cron="5 * * * * ?") public void cronScheduled() { log.info("cron : The time is now {}", dateFormat.format(new Date())); } }
啟用定時任務
package com.zooper.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class); } }