承接上一篇文章【算法数据结构专题】「延时队列算法」史上手把手教你针对层级时间轮(TimingWheel)实现延时队列的开发实战落地(上)】我们基本上对层级时间轮算法的基本原理有了一定的认识,本章节就从落地的角度进行分析和介绍如何通过Java进行实现一个属于我们自己的时间轮服务组件,最后,在告诉大家一下,其实时间轮的技术是来源于生活中的时钟。
【无序列表时间轮】主要是由LinkedList链表和启动线程、终止线程实现。

遍历定时器中所有节点,将剩余时间为 0s 的任务进行过期处理,在执行一个周期。

遍历周期:需要遍历链表中所有节点,时间复杂度 O(n),所以伴随着链表中的元素越来越多,速度也会越来越慢!
无序列表时间轮的长度限制了其适用场景,这里对此进行优化。因此引入了有序列表时间轮。
与无序列表时间轮一样,同样使用链表进行实现和设计,但存储的是绝对延时时间点。

找到执行最后一个过期任务即可,无需遍历整个链表,时间复杂度 O(1),从上面的描述「有序列表定时器」的性能瓶颈在于插入时的任务排序,但是换来的就是缩短了遍历周期。
所以我们如果要提高性,就必须要提升一下插入和删除以及检索的性能,因此引入了「树形有序列表时间轮」在「有序列表定时器」的基础上进行优化,以有序树的形式进行任务存储。
整体流程架构图,如下所示。

对应的原理,在这里就不进行赘述了,之前本人已经有两篇文章对层级式时间轮进行了较为详细的介绍了,有需要的小伙伴,可以直接去前几篇文章去学习,接下来我们进行相关的实现。
时间轮(TimingWheel)是一个存储定时任务的环形队列,数组中的每个元素可以存放一个定时任务列表,其中存放了真正的定时任务,如下图所示。

时间轮的最基本逻辑模型,由多个时间格组成,每个时间格代表当前时间轮的基本时间跨度(tickMs),所以我们先来设计和定义开发对应的时间轮的轮盘模型。命名为Roulette类。
之所以定义这个抽象类
public abstract class Roulette {
// 链表数据-主要用于存储每个延时任务节点
List<TimewheelTask> tasks = null;
// 游标指针索引
protected int index;
// 时间轮轮盘的容量大小,如果是分钟级别,一般就是60个格
protected int capacity;
// 时间轮轮盘的层级,如果是一级,它的上级就是二级
protected Integer level;
private AtomicInteger num = new AtomicInteger(0);
// 构造器
public Roulette(int capacity, Integer level) {
this.capacity = capacity;
this.level = level;
this.tasks = new ArrayList<>(capacity);
this.index = 0;
}
// 获取当前下表的索引对应的时间轮的任务
public TimewheelTask getTask() {
return tasks.get(index);
}
// init初始化操作机制
public List<TimewheelTask> init() {
long interval = MathTool.power((capacity + 1), level);
long add = 0;
TimewheelTask delayTask = null;
for (int i = 0; i < capacity; i++) {
add += interval;
if (level == 0) {
delayTask = new DefaultDelayTask(level);
} else {
delayTask = new SplitDelayTask(level);
}
//已经转换为最小的时间间隔
delayTask.setDelay(add, TimeUnitProvider.getTimeUnit());
tasks.add(delayTask);
}
return tasks;
}
// 索引下标移动
public void indexAdd() {
this.index++;
if (this.index >= capacity) {
this.index = 0;
}
}
// 添加对应的任务到对应的队列里面
public void addTask(TimewheelTask task) {
tasks.add(task);
}
// 给子类提供的方法进行实现对应的任务添加功能
public abstract void addTask(int interval, MyTask task);
}
链表数据-主要用于存储每个延时任务节点。
List<TimewheelTask> tasks = null;
tasks也可以改成双向链表 + 数组的结构:即节点存贮的对象中有指针,组成环形,可以通过数组的下标灵活访问每个节点,类似 LinkedHashMap。
游标指针索引
protected int index;
时间轮轮盘的容量大小,如果是分钟级别,一般就是60个格
protected int capacity;
时间轮轮盘的层级,如果是一级,它的上级就是二级
protected Integer level;
init初始化时间轮轮盘对象模型,主要用于分配分配每一个轮盘上面元素的TimewheelTask,用于延时队列的执行任务线程,已经分配对应的每一个节点的延时时间节点数据。
public List<TimewheelTask> init() {
// 那么整个时间轮的总体时间跨度(interval)
long interval = MathTool.power((capacity + 1), level);
long add = 0;
TimewheelTask delayTask = null;
for (int i = 0; i < capacity; i++) {
add += interval;
if (level == 0) {
delayTask = new ExecuteTimewheelTask(level);
} else {
delayTask = new MoveTimewheelTask(level);
}
//已经转换为最小的时间间隔
delayTask.setDelay(add, TimeUnitProvider.getTimeUnit());
tasks.add(delayTask);
}
return tasks;
}
例如,第一层:20 ,第二层:20^2 ......
//例如 n=7 二进制 0 1 1 1
//a的n次幂 = a的2次幂×a的2次幂 × a的1次幂×a的1次幂 ×a
public static long power(long a, int n) {
int rtn = 1;
while (n >= 1) {
if((n & 1) == 1){
rtn *= a;
}
a *= a;
n = n >> 1;
}
return rtn;
}
主要用于计算时间单位操作的转换
public class TimeUnitProvider {
private static TimeUnit unit = TimeUnit.SECONDS;
public static TimeUnit getTimeUnit() {
return unit;
}
}
代码简介:

获取当前下标的索引对应的时间轮的任务节点
public TimewheelTask getTask() {
return tasks.get(index);
}
在这里我们建立了一个TimewheelBucket类实现了Roulette轮盘模型,从而进行建立对应的我们的层级时间轮的数据模型,并且覆盖了addTask方法。
public class TimewheelBucket extends Roulette {
public TimewheelBucket(int capacity, Integer level) {
super(capacity, level);
}
public synchronized void addTask(int interval, MyTask task) {
interval -= 1;
int curIndex = interval + this.index;
if (curIndex >= capacity) {
curIndex = curIndex - capacity;
}
tasks.get(curIndex).addTask(task);
}
}
添加addTask方法,进行获取计算对应的下标,并且此方法add操作才是对外开发调用的,在这里,我们主要实现了根据层级计算出对应的下标进行获取对应的任务执行调度点,将我们外界BizTask,真正的业务操作封装到这个BizTask模型,交由我们的系统框架进行执行。
public synchronized void addTask(int interval, BizTask task) {
interval -= 1;
int curIndex = interval + this.index;
if (curIndex >= capacity) {
curIndex = curIndex - capacity;
}
tasks.get(curIndex).addTask(task);
}

我们针对于时间轮轮盘的任务点进行设计和定义对应的调度执行任务模型。一个调度任务点,可以帮到关系到多个BizTask,也就是用户提交上来的业务任务线程对象,为了方便采用延时队列的延时处理模式,再次实现了Delayed这个接口,对应的实现代码如下所示:
public interface Delayed extends Comparable<Delayed> {
/**
* Returns the remaining delay associated with this object, in the
* given time unit.
*
* @param unit the time unit
* @return the remaining delay; zero or negative values indicate
* that the delay has already elapsed
*/
long getDelay(TimeUnit unit);
}
@Getter
public abstract class TimewheelTask implements Delayed {
private List<BizTask> tasks = new ArrayList<BizTask>();
private int level;
private Long delay;
private long calDelay;
private TimeUnit calUnit;
public TimewheelTask(int level) {
this.level = level;
}
public void setDelay(Long delay, TimeUnit unit) {
this.calDelay=delay;
this.calUnit=unit;
}
public void calDelay() {
this.delay = TimeUnit.NANOSECONDS.convert(this.calDelay, this.calUnit) + System.nanoTime();
}
public long getDelay(TimeUnit unit) {
return this.delay - System.nanoTime();
}
public int compareTo(Delayed o) {
long d = (getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS));
return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
}
public void addTask(BizTask task) {
synchronized (this) {
tasks.add(task);
}
}
public void clear() {
tasks.clear();
}
public abstract void run();
}
业务任务集合:private List<BizTask> tasks = new ArrayList<BizTask>();
private int level;
private Long delay;
private long calDelay;
private TimeUnit calUnit;
public void addTask(BizTask task) {
synchronized (this) {
tasks.add(task);
}
}
因为对应的任务可能会需要将下游的业务任务进行升级或者降级,所以我们会针对于执行任务点分为,执行任务刻度点和跃迁任务刻度点两种类型。
public class ExecuteTimewheelTask extends TimewheelTask {
public ExecuteTimewheelTask(int level) {
super(level);
}
//到时间执行所有的任务
public void run() {
List<BizTask> tasks = getTasks();
if (CollectionUtils.isNotEmpty(tasks)) {
tasks.forEach(task -> ThreadPool.submit(task));
}
}
}
再次我们就定义执行这些任务的线程池为:
private static ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 100, 3, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(10000),
new MyThreadFactory("executor"), new ThreadPoolExecutor.CallerRunsPolicy());
public class MoveTimewheelTask extends TimewheelTask {
public MoveTimewheelTask(int level) {
super(level);
}
//跃迁到其他轮盘,将对应的任务
public void run() {
List<BizTask> tasks = getTasks();
if (CollectionUtils.isNotEmpty(tasks)) {
tasks.forEach(task -> {
long delay = task.getDelay();
TimerWheel.adddTask(task,delay, TimeUnitProvider.getTimeUnit());
});
}
}
}
致辞整个时间轮轮盘的数据模型就定义的差不多了,接下来我们需要定义运行在时间轮盘上面的任务模型,BizTask基础模型。
public abstract class BizTask implements Runnable {
protected long interval;
protected int index;
protected long executeTime;
public BizTask(long interval, TimeUnit unit, int index) {
this.interval = interval;
this.index = index;
this.executeTime= TimeUnitProvider.getTimeUnit().convert(interval,unit)+TimeUnitProvider.getTimeUnit().convert(System.nanoTime(),TimeUnit.NANOSECONDS);
}
public long getDelay() {
return this.executeTime - TimeUnitProvider.getTimeUnit().convert(System.nanoTime(), TimeUnit.NANOSECONDS);
}
}
主要针对于任务执行,需要交给线程池去执行,故此,实现了Runnable接口。
其中最重要的便是获取延时时间的操作,主要提供给框架的Delayed接口进行判断是否到执行时间了。
public long getDelay() {
return this.executeTime - TimeUnitProvider.getTimeUnit().convert(System.nanoTime(), TimeUnit.NANOSECONDS);
}
最后我们要进行定义和设计开发对应的整体的时间轮层级模型。

public class TimerWheel {
private static Map<Integer, TimewheelBucket> cache = new ConcurrentHashMap<>();
//一个轮表示三十秒
private static int interval = 30;
private static wheelThread wheelThread;
public static void adddTask(BizTask task, Long time, TimeUnit unit) {
if(task == null){
return;
}
long intervalTime = TimeUnitProvider.getTimeUnit().convert(time, unit);
if(intervalTime < 1){
ThreadPool.submit(task);
return;
}
Integer[] wheel = getWheel(intervalTime,interval);
TimewheelBucket taskList = cache.get(wheel[0]);
if (taskList != null) {
taskList.addTask(wheel[1], task);
} else {
synchronized (cache) {
if (cache.get(wheel[0]) == null) {
taskList = new TimewheelBucket(interval-1, wheel[0]);
wheelThread.add(taskList.init());
cache.putIfAbsent(wheel[0],taskList);
}
}
taskList.addTask(wheel[1], task);
}
}
static{
interval = 30;
wheelThread = new wheelThread();
wheelThread.setDaemon(false);
wheelThread.start();
}
private static Integer[] getWheel(long intervalTime,long baseInterval) {
//转换后的延时时间
if (intervalTime < baseInterval) {
return new Integer[]{0, Integer.valueOf(String.valueOf((intervalTime % 30)))};
} else {
return getWheel(intervalTime,baseInterval,baseInterval, 1);
}
}
private static Integer[] getWheel(long intervalTime,long baseInterval,long interval, int p) {
long nextInterval = baseInterval * interval;
if (intervalTime < nextInterval) {
return new Integer[]{p, Integer.valueOf(String.valueOf(intervalTime / interval))};
} else {
return getWheel(intervalTime,baseInterval,nextInterval, (p+1));
}
}
static class wheelThread extends Thread {
DelayQueue<TimewheelTask> queue = new DelayQueue<TimewheelTask>();
public DelayQueue<TimewheelTask> getQueue() {
return queue;
}
public void add(List<TimewheelTask> tasks) {
if (CollectionUtils.isNotEmpty(tasks)) {
tasks.forEach(task -> add(task));
}
}
public void add(TimewheelTask task) {
task.calDelay();
queue.add(task);
}
@Override
public void run() {
while (true) {
try {
TimewheelTask task = queue.take();
int p = task.getLevel();
long nextInterval = MathTool.power(interval, Integer.valueOf(String.valueOf(MathTool.power(2, p))));
TimewheelBucket timewheelBucket = cache.get(p);
synchronized (timewheelBucket) {
timewheelBucket.indexAdd();
task.run();
task.clear();
}
task.setDelay(nextInterval, TimeUnitProvider.getTimeUnit());
task.calDelay();
queue.add(task);
} catch (InterruptedException e) {
}
}
}
}
}
private static Map<Integer, TimewheelBucket> cache = new ConcurrentHashMap<>();
一个轮表示30秒的整体跨度。
private static int interval = 30;
创建整体驱动的执行线程
private static wheelThread wheelThread;
static{
interval = 30;
wheelThread = new wheelThread();
wheelThread.setDaemon(false);
wheelThread.start();
}
static class wheelThread extends Thread {
DelayQueue<TimewheelTask> queue = new DelayQueue<TimewheelTask>();
public DelayQueue<TimewheelTask> getQueue() {
return queue;
}
public void add(List<TimewheelTask> tasks) {
if (CollectionUtils.isNotEmpty(tasks)) {
tasks.forEach(task -> add(task));
}
}
public void add(TimewheelTask task) {
task.calDelay();
queue.add(task);
}
@Override
public void run() {
while (true) {
try {
TimewheelTask task = queue.take();
int p = task.getLevel();
long nextInterval = MathTool.power(interval, Integer.valueOf(String.valueOf(MathTool.power(2, p))));
TimewheelBucket timewheelBucket = cache.get(p);
synchronized (timewheelBucket) {
timewheelBucket.indexAdd();
task.run();
task.clear();
}
task.setDelay(nextInterval, TimeUnitProvider.getTimeUnit());
task.calDelay();
queue.add(task);
} catch (InterruptedException e) {
}
}
}
private static Integer[] getWheel(long intervalTime,long baseInterval) {
//转换后的延时时间
if (intervalTime < baseInterval) {
return new Integer[]{0, Integer.valueOf(String.valueOf((intervalTime % 30)))};
} else {
return getWheel(intervalTime,baseInterval,baseInterval, 1);
}
}
private static Integer[] getWheel(long intervalTime,long baseInterval,long interval, int p) {
long nextInterval = baseInterval * interval;
if (intervalTime < nextInterval) {
return new Integer[]{p, Integer.valueOf(String.valueOf(intervalTime / interval))};
} else {
return getWheel(intervalTime,baseInterval,nextInterval, (p+1));
}
}
到这里相信大家,基本上应该是了解了如何去实现对应的时间轮盘的技术实现过程,有兴趣希望整个完整源码的,可以联系我哦。谢谢大家!
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
给定一个复杂的对象层次结构,幸运的是它不包含循环引用,我如何实现支持各种格式的序列化?我不是来讨论实际实现的。相反,我正在寻找可能会派上用场的设计模式提示。更准确地说:我正在使用Ruby,我想解析XML和JSON数据以构建复杂的对象层次结构。此外,应该可以将该层次结构序列化为JSON、XML和可能的HTML。我可以为此使用Builder模式吗?在任何提到的情况下,我都有某种结构化数据-无论是在内存中还是文本中-我想用它来构建其他东西。我认为将序列化逻辑与实际业务逻辑分开会很好,这样我以后就可以轻松支持多种XML格式。 最佳答案 我最
我有一个涉及多台机器、消息队列和事务的问题。因此,例如用户点击网页,点击将消息发送到另一台机器,该机器将付款添加到用户的帐户。每秒可能有数千次点击。事务的所有方面都应该是容错的。我以前从未遇到过这样的事情,但一些阅读表明这是一个众所周知的问题。所以我的问题。我假设安全的方法是使用两阶段提交,但协议(protocol)是阻塞的,所以我不会获得所需的性能,我是否正确?我通常写Ruby,但似乎Redis之类的数据库和Rescue、RabbitMQ等消息队列系统对我的帮助不大——即使我实现某种两阶段提交,如果Redis崩溃,数据也会丢失,因为它本质上只是内存。所有这些让我开始关注erlang和
我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_
无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD
目录一.加解密算法数字签名对称加密DES(DataEncryptionStandard)3DES(TripleDES)AES(AdvancedEncryptionStandard)RSA加密法DSA(DigitalSignatureAlgorithm)ECC(EllipticCurvesCryptography)非对称加密签名与加密过程非对称加密的应用对称加密与非对称加密的结合二.数字证书图解一.加解密算法加密简单而言就是通过一种算法将明文信息转换成密文信息,信息的的接收方能够通过密钥对密文信息进行解密获得明文信息的过程。根据加解密的密钥是否相同,算法可以分为对称加密、非对称加密、对称加密和非
本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01 客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02 数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit
文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co