// 动态定时任务
@Component
public class DynamicTimedTask {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicTimedTask.class);
// 任务集合
private Map<String, ScheduledFuture<?>> futuresMap = new ConcurrentHashMap<>();
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
// 创建ThreadPoolTaskScheduler线程池
@Bean
private ThreadPoolTaskScheduler threadPoolTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
// 初始化任务列表
@PostConstruct
private void init() {
//模拟新改的定时
List<RobotTimeTask> tasks = new ArrayList<RobotTimeTask>();
RobotTimeTask task1 = new RobotTimeTask();
task1.setId(1);
task1.setName("task1");
task1.setCron("0/5 * * * * ?");
tasks.add(task1);
for(RobotTimeTask task:tasks){
addTask(task);
}
}
/**
* 添加任务
* @param s
*/
public void addTask(RobotTimeTask s){
ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new myRunable(s), new CronTrigger(s.getCron()));
futuresMap.put("task" + s.getId(), future);
}
/**
* 删除任务
* @param key
* @return
*/
public void removeTask(Integer id) {
ScheduledFuture toBeRemovedFuture = futuresMap.remove("task" + id);
if (toBeRemovedFuture != null) {
toBeRemovedFuture.cancel(true);
}
}
/**
* 更新任务
* @param s
*/
public void updateTask(RobotTimeTask s) {
removeTask(s.getId());
addTask(s);
}
/**
* 任务集合
*
*/
public Map<String, ScheduledFuture<?>> getFuturesMap() {
return futuresMap;
}
}
--------------------------------------------------------------------
// 任务实体
@Data
public class RobotTimeTask {
private Integer id;
private String name;
private String cron;
}
---------------------------------------------------------------------
// 手动获取Spring中的bean封装类
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clz) throws BeansException {
return (T)applicationContext.getBean(clz);
}
}
---------------------------------------------------------------------
// 业务Runable
public class myRunable implements Runnable{
private RobotTimeTask s;
public myRunable(RobotTimeTask s){
this.s = s;
}
@Override
public void run() {
System.out.println("taskId:" + s.getId());
//当我们在new Thread时,在run()方法中注入一个service发现注入的service为null。原因是new Thread不在spring容器中,也就无法获得spring中的bean对象,所以我们只能通过ApplicationContext手动来获取bean。
XxxBean xxxService = SpringContextUtil.getBean("xxxService");
xxxService.findALL();
}
}
本文暂时没有评论,来添加一个吧(●'◡'●)