使用timer定时器结合线程池发送消息

  • 定时发送消息主类(Sendmail):
    使用timer定时器结合线程池发送消息
  • 从数据库表中读取符合条件的信息使用线程池进行发送
public class Mytask  extends TimerTask {
    @Override
    public void run() {
        //使用mysql
        List<String> curtask = new ArrayList<>();
        DataSource DruidDataSource = DruidDataSourceFactory.getInstance();
        ExecutorService pool = Executors.newCachedThreadPool();
        try(Connection Connection = DruidDataSource.getConnection()) {
            Statement statement = Connection.createStatement();
            String sql = "select name from test where time between '2019-08-30' and '2019-08-31';";
            ResultSet r = statement.executeQuery(sql);
            while (r.next()){
                curtask.add(r.getString("name"));
            }
            for(int i=0;i<curtask.size();i++){
                pool.submit(new SendMailProcesser(curtask.get(i)));
                }
            pool.shutdown();
            while (!pool.isTerminated()){
                //等待所有线程结束
            }
            System.out.println("main结束时间:"+ now());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    String now(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }
}
  • 发送消息内容:
    使用timer定时器结合线程池发送消息
  • 使用单例模式+volatile关键字+双重检查的方式构建数据池:
public class DruidDataSourceFactory {
    private static volatile DruidDataSource instance = null;
    private DruidDataSourceFactory() {};
    public static DataSource getInstance() {
        if (instance == null) {
            synchronized (DruidDataSourceFactory.class) {
    if (instance == null) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(Constants.getInstance().getProperties().getProperty("username"));
        dataSource.setPassword(Constants.getInstance().getProperties().getProperty("password"));
        dataSource.setUrl(Constants.getInstance().getProperties().getProperty("url"));
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        try {
            dataSource.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        instance = dataSource;
    }
            }
        }
    return instance;
}}
上一篇:Dubbo学习系列之十五(Seata分布式事务方案TCC模式)


下一篇:同一个Tomcat部署多个springboot项目问题