需求场景
(Delay)代码需要延时执行,(Queue)需要不断失败重试
实例
当前时间延时5s执行Task,并在Task中添加一个指定时间执行的延时队列
try {
//第一个参数: 延时任务中需要使用的参数对象,
//第二个参数: 传入new Date()作为延时的基准时间
DelayGetPrise delay = new DelayGetPrise(asset, new Date());
GetOpenPriseTask.addtask(delay);
} catch (Exception e) {
e.printStackTrace();
}
/**
* @Auther: Young
* @Date: 2019/4/13 10:28
* @Description:
*/
@Data
public class DelayGetPrise implements Delayed {
public DelayGetPrise(Asset asset, Date endDate)
{
this.asset = asset;
this.endDate = endDate.getTime();
}
private long endDate;
private Asset asset; //获取的时间
@Override
//调用处传入时间的基础上延时 5s钟后执行task
public long getDelay(TimeUnit unit) {
return (endDate + 5000) - System.currentTimeMillis();
}
@Override
public int compareTo(Delayed o) {
DelayGetPrise jia = (DelayGetPrise) o;
if (this.endDate - jia.getEndDate() > 0)
//时间到达
return 1;
else
return 0;
}
}
/**
* @Auther: Young
* @Date: 2019/4/13 10:27
* @Description:该方法继承AfterSpringLoaded,项目启动后就加载Task,初始化队列等
*/
@Component
public class GetOpenPriseTask implements AfterSpringLoaded {
private static final Logger logger = LoggerFactory.getLogger(GetOpenPriseTask.class);
@Autowired
private AssetService assetService;
@Autowired
private MarketService marketService;
private static final BlockingQueue<DelayGetPrise> getOpenPriseQueue = new DelayQueue<DelayGetPrise>();
public static void addtask(DelayGetPrise dalay) {
getOpenPriseQueue.add(dalay);
}
@Override
public void load() {
while (true) {
try {
logger.info("task任务 开始");
DelayGetPrise prise = getOpenPriseQueue.take();
try {
Asset asset = prise.getAsset();
...
//失败重试
if (失败) {
logger.error("Task任务 数据异常,重试");
//注意此处传入的时间
DelayGetPrise newDelay = new DelayGetPrise(asset, new Date());
GetOpenPriseTask.addtask(newDelay);
//此处不能用break,否则会跳出while(true),关闭队列
continue;
} else {
logger.info("Task任务 正常逻辑执行");
...
logger.info("Task任务完成");
LFExcuter.excute(() -> {
try {
//指定时间延时Task
int delay = asset.getPeriodValue().multiply(new BigDecimal(6)).intValue();
Calendar calUp = Calendar.getInstance();
int delaysecond = RandomUtil.randomInt(delay + 1);
calUp.add(Calendar.SECOND, delaysecond);
logger.info("指定时间:delay: " + delaysecond + "秒");
//在计算好的时间基础上延时
DelayAutoBuy delayAutoUp = new DelayAutoBuy(asset, calUp.getTime(), ExchangeConstant.ORDER_TYPE.UP);
AutoBuyTask.addtask(delayAutoUp);
} catch (Exception e) {
logger.error("指定时间Task任务", e);
}
});
}
} catch (Exception e) {
logger.error("获取队列错误,重试Task任务", e);
GetOpenPriseTask.addtask(prise);
}
} catch (Exception e) {
logger.error("指定时间Task任务 异常:", e);
}
logger.info("Task任务 结束");
}
}
}