springboot使用定时任务、异步

1、定时任务:纯注解方式

@Configuration
@EnableScheduling
@Component
public class TaskConfig {
    //  定时任务:每天凌晨3点跑定时
    @Scheduled(cron = "0 0 3 * * ?")
    public void myTask() {
        System.out.println("定时任务启动。。。。。。");
    }
}

2、异步

         1)注解方式开启异步并设置异步线程池参数

@Configuration
@EnableAsync
public class AsyncConfig {
    /*
    此处成员变量应该使用@Value从配置中读取
     */
    /** Set the ThreadPoolExecutor's core pool size. */
    private int corePoolSize = 10;
    /** Set the ThreadPoolExecutor's maximum pool size. */
    private int maxPoolSize = 200;
    /** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */
    private int queueCapacity = 10;

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }
}

         2)测试异步

@RequestMapping(value = "/api/async")
@RestController
public class AsyncController {

    @Autowired
    private AsyncTask asyncTask;

    @GetMapping(value = "/test")
    public String testAsync() {
        /*
            123-->异步,132-->同步
         */
        System.out.println("1");
        asyncTask.async();
        System.out.println("2");
        return "test";
    }
}

 

@Component
public class AsyncTask {
    @Async
    public void async() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("3");
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值