Spring 隨筆整理 注解
@Scheduled
Annotation @EnableScheduling用來開啟Spring 的schedule task執(zhí)行的能力,一般作用于配置類。該annotation會尋找spring container中的使用@Scheduled聲明的bean。
@EnableScheduling (一般做Application 啟動類上使用 或者 在class 上面是用 //表示開啟定時(shí)任務(wù))
@Scheduled支持多種類型的計(jì)劃任務(wù):
cron:設(shè)置定時(shí)格式;
zone:設(shè)置時(shí)區(qū);
fixedDelay和fixedDelayString: 在上次任務(wù)執(zhí)行完成后延遲多長時(shí)間執(zhí)行;
fixedRate和fixedRateString:上一個(gè)任務(wù)開始執(zhí)行后多長時(shí)間執(zhí)行;
initialDelay 和initialDelayString:表示第一個(gè)延遲執(zhí)行時(shí)間。
下面是Spring boot中使用schedule的示例。
Main class:
@SpringBootApplication
@EnableScheduling // 啟動定時(shí)任務(wù)
public class ScheduleApplicationWithAnnotation {
private static final Logger log = LoggerFactory.getLogger(ScheduleApplicationWithAnnotation.class);
public static void main(String[] args) {
log.info("Start ScheduleApplicationWithAnnotation.. ");
SpringApplication.run(ScheduleApplicationWithAnnotation.class, args);
}
}
Scheduler class:
@Component
public class ScheduleDemo {
private static final Logger log = Logger.getLogger(ScheduleDemo.class);
/**
* 每次方法執(zhí)行完畢后,等待5s再執(zhí)行此方法。
* 同時(shí)只能有個(gè)線程運(yùn)行此方法
*/
@Scheduled(fixedDelay=5000)
public void fixedDelay() {
try {
// 執(zhí)行方法需要10s
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
}
log.info("fixedDelay--");
}
/**
* 每隔5s調(diào)用一次此方法,無論之前的方法是否執(zhí)行完畢
* 同時(shí)可能有N個(gè)線程執(zhí)行此方法
*
*/
@Scheduled(fixedRate=5000)
public void fixedRate() {
try {
// 執(zhí)行方法需要10s
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
}
log.info("fixedRate--");
}
/***
* initialDelay: 第一次調(diào)用此方法前的等待時(shí)間
*
*/
@Scheduled(initialDelay=1000, fixedRate=5000)
public void initialDelayAndfixedRate() {
log.info("initialDelayAndfixedRate--");
}
/**
* 支持cron語法:
* 每個(gè)參數(shù)的意義分別是: second, minute, hour, day of month, month, day of week
*
* 如下:周一至周五,每隔5s執(zhí)行一次方法
*/
@Scheduled(cron="*/5 * * * * SUN-MON")
public void cron() {
log.info("cron--");
}
}
下面是一個(gè)實(shí)際的例子。
Configuration class:
@Configuration
@EnableScheduling
@AutoConfigureAfter({DataSourceConfiguration.class, ServoMetricsAutoConfiguration.class})
public class MethodMonitorAutoConfiguration {
@Bean
public MethodMetricLogJob methodMetricLogJob(MonitorInMemoryCache monitorInMemoryCache, MethodMetricNaming methodMetricNaming){
MethodAvgMetricReader reader = new MethodAvgMetricReader(monitorInMemoryCache.getMonitorRegistry(), methodMetricNaming);
return new MethodMetricLogJob(reader);
}
}
Job class:
@Slf4j
@AllArgsConstructor
public class MethodMetricLogJob {
private final MetricReader metricReader;
@Scheduled(fixedRate = PeriodWindow.DEFAULT_PERIOD)
public void retrieveMetrics4MethodInvoke(){
Runnable runnable = ()->{
Iterable<Metric<?>> metrics = metricReader.findAll();
for (Metric<?> metric : metrics) {
log.info(metric.toString());
}
};
new Thread(runnable, "MethodMetricLog").start();
}
}