To use timing tasks in springboot, you need to annotate annotations on the configuration class or startup class @EnableScheduling
, and annotate annotations on the no-parameter method that is executed regularly. @Scheduled
After the program starts, it will be @Scheduled
executed regularly according to the information provided.
Scheduled parameters
parameter name | meaning |
---|---|
cron = "* * * * * ?" | execution per second |
zone | Time zone, the default is the local time zone TimeZone.getDefault() |
fixedDelay = 1000 | Starts 1 second after the last task execution completes |
fixedDelayString = "1000" | Equivalent to fixedDelay = 1000 |
fixedRate = 1000 | execution per second |
fixedRateString = "1000" | Equivalent to fixedRate = 1000 |
initialDelay = 1000 | The initial delay is 1 second to execute |
initialDelayString = "1000" | Equivalent to initialDelay = 1000 |
cron expression
Don't remember, there are online cron generators online
**
The use of magic numbers is not allowed in the code specification specified by the String company and can be circumvented with these parameters.
code
@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() + "你好~");
}
}
closure
Sometimes we want to close the scheduled task after getting the result we need, such as the print Hello World! task above, and hope that it will be closed after 10 executions.
The timed task can be closed by destroying the bean:
@Component
public class ScheduledHelloTask implements ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledHelloTask.class);
private ApplicationContext applicationContext;
private AtomicInteger atomicInteger = new AtomicInteger();
// 每秒执行
@Scheduled(cron = "* * * * * ?", zone = "Asia/Shanghai")
public void sayHello() {
int count = atomicInteger.incrementAndGet();
if (count <= 10) {
LOGGER.info("第" + count + "次:Hello World!");
return;
}
// 通过销毁bean的方式关闭定时任务
applicationContext.getAutowireCapableBeanFactory().destroyBean(this);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}