该工具类适用于以下场合:
a) 关闭空闲连接。服务器中,有很多客户端的连接,空闲一段时间之后需要关闭之。
b) 缓存。缓存中的对象,超过了空闲时间,需要从缓存中移出。
c) 任务超时处理。在网络协议滑动窗口请求应答式交互时,处理超时未响应的请求。
d)心跳任务
package com.yuan.common.async;
import java.util.Iterator;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yuan.common.collection.DelayItem;
public abstract class TimeoutTask<T> implements Runnable {
private static final Logger log = LoggerFactory.getLogger(TimeoutTask.class);
private DelayQueue<DelayItem<T>> timeoutQueue = new DelayQueue<DelayItem<T>>(); //超时队列
private Thread daemonThread;
private AtomicBoolean running = new AtomicBoolean(true);
private String name;
private Object lock = new Object();
public TimeoutTask(String name){
this.name = name;
}
public void start(){
if(daemonThread == null){
daemonThread = new Thread(this);
daemonThread.setDaemon(true);
daemonThread.setName(name);
daemonThread.start();
}
}
public void stop(){
if(daemonThread != null){
running.compareAndSet(true, false);
daemonThread.interrupt();
}
}
public void join() throws InterruptedException{
if(daemonThread != null){
daemonThread.join();
}
}
@Override
public void run() {
while(running.get()) {
try {
if(timeoutQueue.isEmpty()){//如果超时队列是空的就阻塞守护线程
lock();
}
DelayItem<T> delayItem = timeoutQueue.take();
if(delayItem == null){
continue;
}
process(delayItem.getItem());
//重新开始延迟
delayItem.resetTime();
timeoutQueue.put(delayItem);
} catch (InterruptedException e) {
log.warn(e.getMessage(), e);
}
}
}
protected void lock() throws InterruptedException{
synchronized(lock){
lock.wait();
}
}
protected void unlock(){
synchronized(lock){
lock.notifyAll();
}
}
protected abstract void process(T submit);
public void put(T submit, long timeout, TimeUnit unit){
int minutes = (int)TimeUnit.MINUTES.convert(timeout, unit);
timeoutQueue.put(new DelayItem<T>(submit, minutes));
unlock();
}
public void remove(T submit){
DelayItem<T> delayItem = getDelayItem(submit);
if(delayItem != null){
timeoutQueue.remove(delayItem);
}
}
public void resetTime(T submit){
DelayItem<T> delayItem = getDelayItem(submit);
if(delayItem != null){
delayItem.resetTime();
}
}
protected DelayItem<T> getDelayItem(T submit){
Iterator<DelayItem<T>> it = timeoutQueue.iterator();
while(it.hasNext()){
DelayItem<T> delayItem = it.next();
if(delayItem.getItem() == submit){
return delayItem;
}
}
return null;
}
}
package com.yuan.common.collection;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class DelayItem<T> implements Delayed {
private static final long NANO_ORIGIN = System.nanoTime(); //基准时间
private static final AtomicLong sequencer = new AtomicLong(0); //
private final long sequenceNumber; //FIFO, 保证不会有两个以上的延迟项同时被执行, 先开始延迟的优先执行
private long time;
private final T item;
private final long timeout;
public DelayItem(T submit, int minutes){
this(submit, TimeUnit.NANOSECONDS.convert(minutes, TimeUnit.MINUTES));
}
public DelayItem(T submit, long timeout) {
this.timeout = timeout;
this.time = now() + timeout;
this.item = submit;
this.sequenceNumber = sequencer.getAndIncrement();
}
public void resetTime(){
this.time = now() + timeout;
}
final static long now() {
return System.nanoTime() - NANO_ORIGIN;
}
public T getItem() {
return this.item;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(time - now(), TimeUnit.NANOSECONDS);
}
@Override
public int compareTo(Delayed other) {
if (other == this) // compare zero ONLY if same object
return 0;
if (other instanceof DelayItem) {
DelayItem<?> x = (DelayItem<?>) other;
long diff = time - x.time;
if (diff < 0)
return -1;
else if (diff > 0)
return 1;
else if (sequenceNumber < x.sequenceNumber)
return -1;
else
return 1;
}
long d = (getDelay(TimeUnit.NANOSECONDS) - other
.getDelay(TimeUnit.NANOSECONDS));
return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
}
}
用法:
TimeoutTask<String> timeoutTask = new TimeoutTask<String>("test task") {
protected void process(String submit) {
System.out.println("process : " + submit);
}
};
timeoutTask.put("test", 1, TimeUnit.MINUTES);
timeoutTask.start();
分享到:
相关推荐
基于Java+netty内置时间轮工具处理大批量定时或超时任务工具源码.zip
vCenter中任务、事件清除 适用于:vCenter 6.x,数据库为内置数据库非第三方数据库; 用法:压缩包文件解压到C盘根目录,运行批处理即可,
定义全局线程池,将用户的请求放入自定义队列中,排队等候线程调用,等待超时则自动取消该任务,实现超时可取消的异步任务
任务超时处理是比较常见的需求,Java中对超时任务的处理有两种方式,在文中给大家详细介绍,本文重点给大家介绍Java实现任务超时处理方法,需要的朋友可以参考下
一直用线程池,但有些时候发现线程池无法控制结束某个超时等待的线程任务,所以就勉为其难的自己写了个线程管理~。作用:模仿线程池操作,管理多线程任务,超时,以及完成任务的回调。如果有bug自行处理,服务器挂机...
创建和管理重复任务入门[sudo] npm install timeouter --save例子//Start a basic repeating logvar func = timeouter . add ( {func : function ( ) {console . log ( "Repeating event" )} ,timeout : 1000} )//...
Android 使用AsyncTask设置请求超时的注意事项 final AsyncTaskTools task = new AsyncTaskTools(dialog, doTask, result, context); mTask.execute(蓝牙读卡); new Thread() { public void run() { try { /** ...
Future接口提供方法来检测任务是否被执行完,等待任务执行完获得结果,也可以设置任务执行的超时时间。这个设置超时的方法就是实现Java程 序执行超时的关键。 Future接口是一个泛型接口,严格的格式应该是Future...
不用担心task-running-overtime,因为task框架已经实现了对超时任务的监控,一旦任务超时,任务监控器会将其从线程池中移除,还能帮你自动结束超时任务。 3.任务调度框架性能优良,如果任务队列为空,框架会自动...
单个任务处理的时间比较短 2.将需处理的任务的数量大 使用线程池的好处: 1.减少在创建和销毁线程上所花的时间以及系统资源的开销 2.如不使用线程池,有可能造成系统创建大量线程而导致消耗完系统内存以及”过度切换...
主要介绍了PHP进行批量任务处理不超时的解决方法,结合实例形式简单分析了php结合ajax进行异步处理实现批量任务不超时的相关技巧,需要的朋友可以参考下
.net C#线程超时的解决方案,使用的时候在被调线程入口调用一下这个方法就可以。更多详细代码见附件 Report.RegisterThread(Report.GetCurrentWin32ThreadID(),Thread.CurrentThread); #region 获取当取线程的...
定时任务SpringTask -超时15分钟取消订单
.net C#线程超时的解决方案,使用的时候在被调线程入口调用一下这个方法就可以。更多详细代码见附件 Report.RegisterThread(Report.GetCurrentWin32ThreadID(),Thread.CurrentThread); #region 获取当取线程的...
任务执行超时, 强制结束 任务依赖配置, A任务完成后再执行B任务 账户权限控制 任务类型 shell任务 在任务节点上执行shell命令, 支持任务同时在多个节点上运行 HTTP任务 访问指定的URL地址, 由调度器直接执行, 不...
任务执行超时, 强制结束 任务依赖配置, A任务完成后再执行B任务 账户权限控制 任务类型 shell任务 在任务节点上执行shell命令, 支持任务同时在多个节点上运行 HTTP任务 访问指定的URL地址, 由调度器直接执行, 不...
5.雇主发布任务会有时间限制,超时不审核就会自动审核通过,佣金进入用户帐号中, 6.任务可置顶,可以付费置顶,按天算, 7.雇主可以自己审核任务,可以留言用户是否完成, 8.用户提现后会扣除一定数额的费用,给...
5.雇主发布任务会有时间限制,超时不审核就会自动审核通过,佣金进入用户帐号中, 6.任务可置顶,可以付费置顶,按天算, 7.雇主可以自己审核任务,可以留言用户是否完成, 8.用户提现后会扣除一定数额的费用,给...
Quartz.net作业调度自定义定时执行任务多任务执行c#,定时执行任务,如超时取消订单,自动确认收货等等