springboot多线程定时任务

2021-02-04 04:14

阅读:469

标签:syn   config   for   complete   repo   log   hello   awr   utils   

package com.llf.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(20);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("lawrence-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }

}

  多线程异步执行

package com.llf.utils;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class Text {

    @Async
    public void sayHellot(int i){
        System.out.println(i+"---"+System.currentTimeMillis());
    }

}

  定时执行,时间设置参考:https://www.cnblogs.com/xiang--liu/p/11378860.html

package com.llf.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
@Lazy(false)
public class Sd {

    @Autowired
    Text text;

    @Scheduled(cron = "*/2 * * * * ?")
    public void text(){
        text.sayHellot(1);
    }
}

  

springboot多线程定时任务

标签:syn   config   for   complete   repo   log   hello   awr   utils   

原文地址:https://www.cnblogs.com/-llf/p/12797827.html


评论


亲,登录后才可以留言!