这一小节来学习Spring定时器
我们将建立一个应该,每五秒钟打印一次系统时间。
新建定时器类,如下
1 package cn.tiny77.guide02; 2 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; 8 import org.springframework.scheduling.annotation.Scheduled; 9 import org.springframework.stereotype.Component; 10 11 @Component 12 public class ScheduledTasks { 13 14 private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); 15 16 private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); 17 18 @Scheduled(fixedRate = 5000) 19 public void reportCurrentTime() { 20 log.info("The time is now {}", dateFormat.format(new Date())); 21 } 22 }
@Schedule 注释定义方法执行的时间。
这里使用的是fixedRate。
fixedRate 和 fixedDelay 区别:
fixedRate指的是从上一个任务开始到当前任务开始的时间间隔
fixedDelay指的是从上一个任务结束到当前任务开始的时间间隔
也可以使用
@Schedule(cron="...")来定义更为复杂的任务执行时间。
下面来写程序Main函数。
如下
1 package cn.tiny77.guide02; 2 3 import org.springframework.boot.autoconfigure.SpringBootApplication; 4 import org.springframework.scheduling.annotation.EnableScheduling; 5 6 @EnableScheduling 7 @SpringBootApplication 8 public class App 9 { 10 public static void main( String[] args ) 11 { 12 System.out.println( "Hello World!" ); 13 } 14 }
@EnableScheduling保证后台定时器被创建,没有它,则不会有定时任务产生。