java定时任务

用法:
	开启任务调度:@EnableScheduling
	定义一个类,把这个类加入到容器中,在方法上加
	 @Scheduled(cron = "百度表达式即可")
	 
	复杂的任务: 1,默认的线程池大小是1,可以在配置文件中配置task
			   2,async
			   3,手写线程池+从spring中获取线程池单例




示例:
	普通类从容器中取对象取出线程池,单例线程池和执行线程
package com.sm.qy28.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringConfigUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;


    public static <T> T getBean(Class<T> clazz) {
        return (T) applicationContext.getBean(clazz);
    }


    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringConfigUtils.applicationContext = applicationContext;
    }
}
package com.sm.qy28.common.async;

import com.sm.qy28.common.utils.SpringConfigUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.swing.*;

//单例线程池,从spring中获取
public class AsyncManager {

    private static ThreadPoolTaskExecutor threadPoolTaskExecutor;
    private static AsyncManager asyncManager;

    private AsyncManager() {
        threadPoolTaskExecutor= SpringConfigUtils.getBean(ThreadPoolTaskExecutor.class);
    }


    public static AsyncManager getInstance(){
        if(asyncManager==null){
         return    asyncManager= new AsyncManager();
        }
        return asyncManager;
    }

//    异步执行线程
    public  void execute(Runnable runnable){
        threadPoolTaskExecutor.execute(runnable);
    }
}

package com.sm.qy28.common.async;

public class AsyncFactory {

    public static Runnable xxxx(){
        Runnable runnable=()->{

        };
        return runnable;
    }

}

springboot配置文件中配置线程池的线程
spring.task.execution.pool.core-size=50
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值