springboot中要使用定时任务须要在配置类或启动类上标注注解@EnableScheduling
,并在定时执行的无参方法上标注注解@Scheduled
,程序启动后会根据@Scheduled
所提供的信息定时执行。spring
参数名 | 含义 |
---|---|
cron = "* * * * * ?" | 每秒执行 |
zone | 时区,默认为本地时区TimeZone.getDefault() |
fixedDelay = 1000 | 上次任务执行完成后1秒开始 |
fixedDelayString = "1000" | 等同fixedDelay = 1000 |
fixedRate = 1000 | 每秒执行 |
fixedRateString = "1000" | 等同fixedRate = 1000 |
initialDelay = 1000 | 初始延时1秒执行 |
initialDelayString = "1000" | 等同initialDelay = 1000 |
不用记,网上有在线cron生成器springboot
@Component public class ScheduledHelloTask { private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledHelloTask.class); private int getSecond() { return Calendar.getInstance().get(Calendar.SECOND); } // 每秒执行 @Scheduled(cron = "* * * * * ?", zone = "Asia/Shanghai") public void sayHello() { LOGGER.info("Hello World!"); } // 任务执行完成后延时1秒开始 @Scheduled(fixedDelay = 1000) public void sayHello1() throws InterruptedException { LOGGER.info(getSecond() + "春暖花开~"); Thread.sleep(1000); } // 每秒执行,效果等同{cron = "* * * * * ?"} @Scheduled(initialDelay = 2000, fixedRate = 1000) public void sayHello2() throws InterruptedException { LOGGER.info(getSecond() + "你好~"); } }
有时候咱们在获得本身须要的结果后想关闭定时任务,好比经过前台发送连接来开启上面的打印Hello World!任务,但愿它执行10次后关闭。
此时就不能在类ScheduledHelloTask
上添加@Component
了, 由于咱们须要动态注册bean来实现。改造以下:app
@EnableScheduling public class ScheduledHelloTask { private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledHelloTask.class); private AtomicInteger atomicInteger = new AtomicInteger(); public AtomicInteger getAtomicInteger() { return atomicInteger; } public void setAtomicInteger(AtomicInteger atomicInteger) { this.atomicInteger = atomicInteger; } // 每秒执行 @Scheduled(cron = "* * * * * ?", zone = "Asia/Shanghai") public void sayHello() { int count = atomicInteger.incrementAndGet(); LOGGER.info("第" + count + "次:Hello World!"); } }
添加ScheduleController
,代码以下:this
@RestController public class ScheduleController { private static final String BEAN_NAME = "scheduledHelloTask"; @GetMapping public String sayHi() throws InterruptedException { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); if (!applicationContext.containsBean(BEAN_NAME)) { applicationContext.register(ScheduledHelloTask.class); } applicationContext.refresh(); while (applicationContext.containsBean(BEAN_NAME)) { if (applicationContext.getBean(ScheduledHelloTask.class).getAtomicInteger().get() == 10) { applicationContext.removeBeanDefinition(BEAN_NAME); } } return "success"; } }
两次访问localhost:8080
,结果以下:
atom
预期效果已实现!代码规范