Springboot timed task @Scheduled use
Scheduled is not suitable for dynamically modifying the frequency. If you want to dynamically modify the frequency, please refer to:
Springboot2.x integrated quartz to achieve dynamic timing tasks
1. Add @EnableScheduling to the startup class to start timing tasks
@SpringBootApplication
@EnableScheduling
@Slf4j
public class MaintainStarter {
public static void main(String[] args) {
SpringApplication.run(MaintainStarter.class, args);
}
}
2. Create a thread pool
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
private static final int MAX_POOL_SIZE = Math.max(CORE_POOL_SIZE * 4, 256);
private static final int KEEP_ALIVE_TIME = 10; //允许线程空闲时间(单位为秒)
private static final int QUEUE_CAPACITY = 200; // 缓冲队列数
private static final int AWAIT_TERMINATION = 60;//线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁
private static final Boolean WAIT_FOR_TASKS_TO_COMPLETE_ON_SHUTDOWN = true;//用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
@Bean("logTaskExecutor")
public ThreadPoolTaskExecutor logTaskExecutor() {
return getThreadPoolTaskExecutor("log-thread-");
}
@Bean("schedulingTaskExecutor")
public ThreadPoolTaskExecutor schedulingTaskExecutor() {
return getThreadPoolTaskExecutor("scheduling-thread");
}
private ThreadPoolTaskExecutor getThreadPoolTaskExecutor(String s) {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
taskExecutor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
taskExecutor.setQueueCapacity(QUEUE_CAPACITY);
taskExecutor.setThreadNamePrefix(s);
taskExecutor.setWaitForTasksToCompleteOnShutdown(WAIT_FOR_TASKS_TO_COMPLETE_ON_SHUTDOWN);
taskExecutor.setAwaitTerminationSeconds(AWAIT_TERMINATION);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}
3. Use @Scheduled
@Slf4j
@Component
public class SystemScheduling {
/**
* 定时任务例子
*/
@Async("schedulingTaskExecutor")
@Scheduled(cron = CronConstant.ONE_HOUR)
public void logging() throws MalformedObjectNameException, InstanceNotFoundException, ReflectionException {
log.info("SystemScheduling = now : [{}] memory : [{}] cpu : [{}]", new Date(), Runtime.getRuntime().totalMemory() / (1024 * 1024) + "M", getCpu());
}
private int getCpu() throws MalformedObjectNameException, ReflectionException, InstanceNotFoundException {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
AttributeList list = mbs.getAttributes(name, new String[]{
"ProcessCpuLoad"});
if (list.isEmpty()) return 0;
Attribute att = (Attribute) list.get(0);
Double value = (Double) att.getValue();
if (value == -1.0) return 0;
return (int) ((int) (value * 1000) / 10.0);
}
}
public class CronConstant {
/**
* 每小时执行一次
*/
public static final String ONE_HOUR = "0 0 0/1 * * ? ";
}
As for the corresponding Cron expression, it can be generated through https://cron.qqe2.com
Scheduled parameter description:
1. cron: expression, specify the task to be executed at a specific time;
2. fixedDelay: indicate how long to execute the task again after the completion of the last task execution, the parameter type is long, the unit is ms;
3. fixedDelayString: the meaning is the same as fixedDelay, Only the parameter type becomes String;
4.fixedRate: indicates that the task is executed at a certain frequency, that is, the time interval between each start is the same, the parameter type is long, the unit is ms;
5.fixedRateString: has the same meaning as fixedRate, but the parameter The type is changed to String;
6.initialDelay: indicates how long to delay the task to be executed for the first time, the parameter type is long, the unit is ms;
7.initialDelayString: the meaning is the same as initialDelay, but the parameter type is changed to String;
8.zone: time zone , The default is the current time zone.