读取外部文件获取定时任务cron,开启多线程定时任务

该博客介绍了如何在Java SpringBoot应用中实现定时任务的配置和管理,包括读取外部cron配置文件,动态刷新任务,以及在项目启动时自动初始化定时任务。示例代码展示了使用`ScheduledTask`接口和`CronConfiger`类来处理定时任务的创建、删除和修改。
摘要由CSDN通过智能技术生成

读取外部文件cron

package com.psbc.sendbatchfile.scheduletask;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class CronConfiger {
	
	private  Properties config ;
	
	private String FILE_NAME = "hw_cron_one.properties";
	
	private static CronConfiger instance;
	
	private CronConfiger(String fileName){
		
		this.config = new Properties();
		if(fileName != null){
			this.FILE_NAME = fileName;
			InputStream in = null;
			try {
				String configDir = System.getProperty("PTX_HOME");
				configDir = "C:\\Users\\swhewenjie\\Desktop\\conf\\one";
				String configFile = configDir + File.separatorChar +"config"+File.separatorChar +this.FILE_NAME;
				File f = new File(configFile);
				if(!f.exists()){
					System.out.println("can not find file :" +configFile);
//					in = ClassLoader.getSystemResourceAsStream(configFile);
					in = this.getClass().getClassLoader().getResourceAsStream(this.FILE_NAME);
				} else {
					System.out.println("load config file :" +configFile);
					in = new FileInputStream(configFile);
				}
				
				this.config.load(in);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(in != null){
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	public static CronConfiger getInstance(){
		
//		if(instance == null){
//			instance= new DCConfiger("dc_conf.properties");
//		}
		
		instance= new CronConfiger("hw_cron_one.properties");
		
		return instance;
	}
	
	public static String getStrValue(String name,String def){
		
		return getInstance().getProperty(name, def);
		
	}
	
	public static int getIntValue(String name,int def){
		
		String val = getStrValue(name,def+"");
		int ret = def;
		try{
			ret = Integer.valueOf(val);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return ret;
	}
	
	
	public String getProperty(String name,String def){
		
		return this.config.getProperty(name, def);
		
	}
	
	public void setProperty(String name,String value){
		
		this.config.put(name, value);
		
	}
		

}

读取外部文件还有其他形式

定时任务的开启和删除和修改

package com.psbc.sendbatchfile.scheduletask;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;
import com.psbc.sendbatchfile.service.DayAllHdoopService;
import com.psbc.sendbatchfile.service.SysSendSchemadbService;
import com.psbc.sendbatchfile.service.YesterdayDateService;

import lombok.extern.slf4j.Slf4j;

@Component
@Configurable
@EnableScheduling
@Slf4j
public class ScheduledTask implements SchedulingConfigurer {
	private volatile ScheduledTaskRegistrar registrar;
	private final ConcurrentHashMap<Integer, ScheduledFuture<?>> scheduledFutures = new ConcurrentHashMap<Integer, ScheduledFuture<?>>();
	private final ConcurrentHashMap<Integer, CronTask> cronTasks = new ConcurrentHashMap<Integer, CronTask>();

	@Autowired
	private DayAllHdoopService dayAllHdoopService;
	
	@Autowired
	private SysSendSchemadbService sysSendSchemadbService ;
	
	@Autowired
	private YesterdayDateService yesterdayDateService;
	

	@Override
	public void configureTasks(ScheduledTaskRegistrar registrar) {
		// TODO 自动生成的方法存根
		// 设置30个线程,默认是单线程
		registrar.setScheduler(Executors.newScheduledThreadPool(30));
		this.registrar = registrar;
	}

	/**
	 * 刷新任务
	 */
	public void refresh() {
		Map<Integer, String> map = new LinkedHashMap<>();
		// 取消已经删除的策略任务
		Set<Integer> sids = scheduledFutures.keySet();
		String dayallhdoop = CronConfiger.getStrValue("hwCron_dayallhdoop_one", null);
		if (dayallhdoop!=null&&!"".equals(dayallhdoop)) {
			map.put(1, dayallhdoop);
		}
		String syssendschemadb = CronConfiger.getStrValue("hwCron_syssendschemadb_one", null);
		if (syssendschemadb!=null&&!"".equals(syssendschemadb)) {
			map.put(2, syssendschemadb);
		}
		String yesterdaydate = CronConfiger.getStrValue("hwCron_yesterdaydate_one", null);
		if (yesterdaydate!=null&&!"".equals(yesterdaydate)) {
			map.put(3, yesterdaydate);
		}
		for (Integer sid : sids) {
			if (!exists(map, sid)) {
				if (sid==1) {
					log.debug("删除定时任务—— 一期日全量数据,时间:{}",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
				}else if(sid==2){
					log.debug("删除定时任务—— 一期数据管控元数据,时间:{}",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
				}else if(sid==3){
					log.debug("删除定时任务——  一期日增量数据,时间:{}",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
				};
				scheduledFutures.get(sid).cancel(false);
			}
		}
		if (map != null) {
			for (Map.Entry<Integer, String> entry : map.entrySet()) {
				String expression = entry.getValue();// cron表达式
				Integer sid = entry.getKey();// 每个的id
				// 计划任务表达式为空则跳过
				if (StringUtils.isEmpty(expression)) {
					continue;
				}
				// 计划任务已存在并且表达式未发生变化则跳过
				if (scheduledFutures.containsKey(sid) && cronTasks.get(sid).getExpression().equals(expression)) {
					continue;
				}
				// 如果策略执行时间发生了变化,则取消当前策略的让你无
				if (scheduledFutures.containsKey(sid)) {
					scheduledFutures.get(sid).cancel(false);
					scheduledFutures.remove(sid);
					cronTasks.remove(sid);
				}
				CronTask task = new CronTask(new Runnable() {

					@Override
					public void run() {
						// TODO 自动生成的方法存根
						// 每个执行任务实际需要执行的具体业务逻辑
						if (sid==1) {
							log.debug("开始执行定时任务—— 一期日全量数据,时间:{}",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
							dayAllHdoopService.dayAllHdoop();
						}else if(sid==2){
							log.debug("开始执行定时任务—— 一期数据管控元数据,时间:{}",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
							sysSendSchemadbService.sysSendSchemadb();
						}else if(sid==3){
							log.debug("开始执行定时任务——  一期日增量数据,时间:{}",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
							yesterdayDateService.yesterdayDate();
						};
					}
				}, expression);
				ScheduledFuture<?> future = registrar.getScheduler().schedule(task.getRunnable(), task.getTrigger());
				cronTasks.put(sid, task);
				scheduledFutures.put(sid, future);
				if (sid==1) {
					log.debug("即将开始定时任务—— 一期日全量数据,cron:{}",expression);
				}else if(sid==2){
					log.debug("即将开始定时任务—— 一期数据管控元数据,cron:{}",expression);
				}else if(sid==3){
					log.debug("即将开始定时任务——  一期日增量数据,cron:{}",expression);
				};
			}
		}

	}

	private boolean exists(Map<Integer, String> map, Integer tid) {
		Set<Integer> keySet = map.keySet();
		for (Integer i : keySet) {
			if (i == tid) {
				return true;
			}
		}
		return false;
	}

}

项目启动自动初始化

package com.psbc.sendbatchfile.scheduletask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class ApplicationRunnerImpl implements ApplicationRunner{
	@Autowired
	private ScheduledTask scheduledTask;
	@Override
	public void run(ApplicationArguments args) throws Exception {
		// TODO 自动生成的方法存根
		log.debug("自动刷新定时任务---开始");
		scheduledTask.refresh();
		log.debug("自动刷新定时任务--结束");
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值