场景:定时从Zabix监控系统中更新数据
文章目录
配置
1、 在启动类上增加注解@EnableScheduling,开启功能
@EnableScheduling//开启定时器
@SpringBootApplication
@MapperScan("com.hkvision.hire.mapper")
public class HireApplication {
public static void main(String[] args) {
SpringApplication.run(HireApplication.class, args);
}
}
2、在需要定时的方法上增加注解@Scheduled(fixedDelay = 1000)
@Component
public class ScheduledTest {
@Scheduled(fixedDelay = 1000)
public void test(){
System.out.println("经哥好帅");
}
}
配置多线程执行Scheduled
@Schduled 默认是基于单线程执行,
所有的定时任务串行执行,这就可能导致运行时间久的任务,会影响到下一个运行周期的任务。如果需要基于多线程执行,则需要配置。
详细配置应用下大哥们写的文章
https://blog.csdn.net/qq_35067322/article/details/103982304
# 任务调度线程池
# 任务调度线程池大小 默认 1 建议根据任务加大
spring.task.scheduling.pool.size=1
# 调度线程名称前缀 默认 scheduling-
spring.task.scheduling.thread-name-prefix=scheduling-
# 线程池关闭时等待所有任务完成
spring.task.scheduling.shutdown.await-termination=
# 调度线程关闭前最大等待时间,确保最后一定关闭
spring.task.scheduling.shutdown.await-termination-period=
# 任务执行线程池配置
# 是否允许核心线程超时。这样可以动态增加和缩小线程池
spring.task.execution.pool.allow-core-thread-timeout=true
# 核心线程池大小 默认 8
spring.task.execution.pool.core-size=8
# 线程空闲等待时间 默认 60s
spring.task.execution.pool.keep-alive=60s
# 线程池最大数 根据任务定制
spring.task.execution.pool.max-size=
# 线程池 队列容量大小
spring.task.execution.pool.queue-capacity=
# 线程池关闭时等待所有任务完成
spring.task.execution.shutdown.await-termination=true
# 执行线程关闭前最大等待时间,确保最后一定关闭
spring.task.execution.shutdown.await-termination-period=
# 线程名称前缀
spring.task.execution.thread-name-prefix=task-
定时参数
可用情况:
- 上次任务执行完后多少秒执行fixedDelay;固定多少秒后执行fixedRate
- 更复杂的场景使用@Scheduled cron表达式