線程池與定時任務

/**
*創建線程池
*/

public class ThreadPoolManager {

    private static ThreadPoolManager instance;

    public synchronized static ThreadPoolManager getsInstance() {
        if (instance == null) {
            instance = new ThreadPoolManager();
        }
        return instance;
    }
    //根據cpu的數量動態的配置核心線程數和最大線程數
    private static final int CPU_COUNT  = Runtime.getRuntime().availableProcessors();
    //核心線程數 = CPU核心數 + 1
    private static final int corePoolSize  = CPU_COUNT + 1;
    //線程池最大線程數 = CPU核心數 * 2 + 1
    private static final int maximumPoolSize = CPU_COUNT * 2 + 1;
    //非核心線程閒置時超時30s
    private static final int KEEP_ALIVE = 6000;

    public ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            KEEP_ALIVE,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    public static void main(String[] args) {
        System.out.println(CPU_COUNT);
    }

}

import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.logging.Logger;

public class syncTestThread implements  Runnable {
   private Logger logger = (Logger) LoggerFactory.getLogger(syncTestThread.class);
    @Override
    public void run() {
		//線程需要執行的方法
        logger.info("----------------------執行結束---------------------------------");
    }
}

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadPoolExecutor;

public class Syns implements Job {
    private Logger logger = LoggerFactory.getLogger(Syns.class);
    private static final int pageSize = 1000;
    private static Syns instance;

    public static Syns getCurrentInstance() {
        if (instance == null) {
            instance = new Syns();
        }
        return instance;
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        test();
    }
    public void test(){
        ThreadPoolExecutor threadPoolExecutor = ThreadPoolManager.getsInstance().threadPoolExecutor;
        //將要執行的線程提交到線程池
       threadPoolExecutor.submit(new syncTestThread());
    }
}

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 *  實現作業的調度
 *job.properties 配置文件,corn 
 */
public class NewQuartzPlugin implements IPlugin {
    private SchedulerFactory sf = null;
    private Scheduler sched = null;
    private String config = "/job.properties";
    private Properties properties;

    public NewQuartzPlugin(String config) {
        this.config = config;
    }

    public NewQuartzPlugin() {
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public boolean start() {
        sf = new StdSchedulerFactory();
        try {
            sched = sf.getScheduler();
        } catch (SchedulerException e) {
            new RuntimeException(e);
        }
        loadProperties();
        Enumeration enums = properties.keys();
        while (enums.hasMoreElements()) {
            String key = enums.nextElement() + "";
            if (!key.endsWith("job")) {
                continue;
            }
            String cronKey = key.substring(0, key.indexOf("job")) + "cron";
            String enable = key.substring(0, key.indexOf("job")) + "enable";
            if (isDisableJob(enable)) {
                continue;
            }
            String jobClassName = properties.get(key) + "";
            String jobCronExp = properties.getProperty(cronKey) + "";
            Class clazz;
            try {
                clazz = Class.forName(jobClassName);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            JobDetail job = newJob(clazz).withIdentity(jobClassName,
                    jobClassName).build();
            CronTrigger trigger = newTrigger()
                    .withIdentity(jobClassName, jobClassName)
                    .withSchedule(cronSchedule(jobCronExp)).build();
            Date ft = null;
            try {
                ft = sched.scheduleJob(job, trigger);
                sched.start();
            } catch (SchedulerException ee) {
                new RuntimeException(ee);
            }
            System.out.println(job.getKey() + " has been scheduled to run at: " + ft
                    + " and repeat based on expression: "
                    + trigger.getCronExpression());
        }
        return true ;
    }

    private boolean isDisableJob(String enable) {
        return Boolean.valueOf(properties.get(enable) + "") == false;
    }

    private void loadProperties() {
        properties = new Properties();
        InputStream is = NewQuartzPlugin.class.getResourceAsStream(config);
        try {
            properties.load(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean stop() {
        try {
            sched.shutdown();
        } catch (SchedulerException e) {
            e.printStackTrace();
            System.out.println("shutdown error");
            return false;
        }
        return true;
    }

    public static void main(String []args)  {
        NewQuartzPlugin plugin = new NewQuartzPlugin();
        plugin.start();
        System.out.println("執行成功!!!");

    }
}
job.properties
datax.job= 執行方法類路徑(即Syns.class路徑)
datax.cron= 0 30 23 * * ?
datax.enable=true

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章