Springboot定时任务@Scheduled使用

Springboot定时任务@Scheduled使用

Scheduled不适合做动态修改频率,如果想动态修改频率可以参考:
Springboot2.x 集成 quartz实现动态定时任务

1、启动类上添加@EnableScheduling开启定时任务

@SpringBootApplication
@EnableScheduling
@Slf4j
public class MaintainStarter {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(MaintainStarter.class, args);
    }
}

2、创建线程池

@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、使用@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 * * ? ";
}

至于对应的Cron表达式可以通过 https://cron.qqe2.com 生成

Scheduled参数说明:
在这里插入图片描述
1.cron:表达式,指定任务在特定时间执行;
2.fixedDelay:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms;
3.fixedDelayString:与fixedDelay含义一样,只是参数类型变为String;
4.fixedRate:表示按一定的频率执行任务,即每次开始执行的时间间隔一致,参数类型为long,单位ms;
5.fixedRateString: 与fixedRate的含义一样,只是将参数类型变为String;
6.initialDelay:表示延迟多久再第一次执行任务,参数类型为long,单位ms;
7.initialDelayString:与initialDelay的含义一样,只是将参数类型变为String;
8.zone:时区,默认为当前时区。

猜你喜欢

转载自blog.csdn.net/weixin_38045214/article/details/114968188