计时器回调函数 CountdownTimeoutCallBackInterface
public interface CountdownTimeoutCallBackInterface {
Boolean stop();
void doInTimeout();
}
计时器工具 CountdownUtil
public class CountdownUtil {
private static Logger logger = LoggerFactory.getLogger(CountdownUtil.class);
/**
*
* @param totalCount 计时总时长(毫秒)
* @param delay 每次执行延迟时间(毫秒)
* @param callBackInterface 回调函数
*/
public static void countdown(Long totalCount, Long delay, CountdownTimeoutCallBackInterface callBackInterface) {
logger.debug("Countdown start---> count = {} , delay = {} .", totalCount, delay);
//step1 计算出循环执行次数
long step = totalCount / delay;
//step2 检查是否超出执行次数
while (step-- >= 0) {
try {
Thread.sleep(delay);
//step3 是否由满足停止计时条件
if (callBackInterface.stop()) {
logger.debug("Countdown stop . ");
return;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//step4 计时结束后执行的方法
logger.debug("Countdown timout . ");
callBackInterface.doInTimeout();
}
}