package com.haoruan.timer; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.SynchronousQueue; public class InitializeProjectTask extends TimerTask { private final Timer timer; private final SynchronousQueue<Boolean> queue; private final HashMap<Object, Object> paramMap; private final Map<String, String> headerMap; private static final int limit = 12; private int curCount = 0; public InitializeProjectTask(Timer timer, SynchronousQueue<Boolean> queue, HashMap<Object, Object> paramMap, Map<String, String> headerMap) { this.timer = timer; this.queue = queue; this.paramMap = paramMap; this.headerMap = headerMap; } @Override public void run() { try { if(curCount <= limit){ //异步任务处理,项目初始化,初始化基础配置数据,创建框架角色 DONE状态即可 if(!"DONE".equals("结果")){ curCount++; }else { this.timer.cancel(); try { this.queue.put(true); } catch (InterruptedException e) { e.printStackTrace(); } } }else { this.timer.cancel(); try { this.queue.put(true); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (Exception e) { //抛出异常提示 异步任务处理失败 e.printStackTrace(); } } }
package com.haoruan.timer; import org.springframework.security.web.header.Header; import java.util.HashMap; import java.util.Timer; import java.util.concurrent.SynchronousQueue; public class TimerTest { public static void main(String[] args) { try { SynchronousQueue<Boolean> queue = new SynchronousQueue<>(); Timer timer = new Timer(); HashMap<Object, Object> paramMap = new HashMap<>(); HashMap<String, String> hederMap = new HashMap<>(); InitializeProjectTask task = new InitializeProjectTask(timer,queue,paramMap,hederMap); timer.scheduleAtFixedRate(task, 1000*5 , 1000*2);//0:任务 1:延迟时间 2:间隔时间 Boolean result = queue.take(); } catch (InterruptedException e) { e.printStackTrace(); } } }