package com.dy.common.mw.core; 
 | 
  
 | 
import org.apache.logging.log4j.LogManager; 
 | 
import org.apache.logging.log4j.Logger; 
 | 
  
 | 
import java.util.Timer; 
 | 
import java.util.TimerTask; 
 | 
  
 | 
/** 
 | 
 * @Author: liurunyu 
 | 
 * @Date: 2024/11/21 13:41 
 | 
 * @Description 
 | 
 */ 
 | 
public class CoreTimer extends TimerTask { 
 | 
  
 | 
    private static final Logger log = LogManager.getLogger(CoreTimer.class.getName()) ; 
 | 
  
 | 
    private static final CoreTimer instance = new CoreTimer() ; 
 | 
  
 | 
    private Long workInterval = 100L ;//核心线程暂停间隔 
 | 
  
 | 
    private Timer timer; 
 | 
  
 | 
    private boolean stop; 
 | 
  
 | 
    private CoreTimer(){ 
 | 
        this.timer = new Timer(); 
 | 
        this.stop = false ; 
 | 
    } 
 | 
  
 | 
    public static CoreTimer getInstance(){ 
 | 
        return instance ; 
 | 
    } 
 | 
  
 | 
    public void stop(){ 
 | 
        this.stop = true ; 
 | 
        if(this.timer != null){ 
 | 
            this.timer.cancel(); 
 | 
        } 
 | 
    } 
 | 
    public boolean isStop(){ 
 | 
        return this.stop ; 
 | 
    } 
 | 
  
 | 
    /** 
 | 
     * 设置/核心线程暂停间隔 
 | 
     * @param workInterval /核心线程暂停间隔 
 | 
     */ 
 | 
    public void setSleep(Long workInterval){ 
 | 
        this.workInterval = workInterval ; 
 | 
    } 
 | 
  
 | 
    public void start(){ 
 | 
        this.timer.schedule(this, 0 , this.workInterval); 
 | 
    } 
 | 
  
 | 
    /** 
 | 
     * TimerTask的run方法 
 | 
     */ 
 | 
    @Override 
 | 
    public void run() { 
 | 
        try{ 
 | 
            /** 
 | 
             * 此处取出当前队列的节点数量,作为一个定量count处理, 
 | 
             * 原因: 
 | 
             * 在处理定量count过程中,可能有的节点又回到队列中,也可能新生节点进入队列中,即在处理过程中,队列可能又增长了 
 | 
             */ 
 | 
            int count = CoreUnit.taskQueue.size() ; 
 | 
            while(count > 0){ 
 | 
                CoreTask task = (CoreTask)CoreUnit.taskQueue.pop() ; 
 | 
                if(task != null){ 
 | 
                    task.execute(); 
 | 
                } 
 | 
                count-- ; 
 | 
            } 
 | 
        }catch(Exception e){ 
 | 
            log.error("核心线程发生异常" + (e.getMessage() == null ? "" : (":" + e.getMessage())), e);; 
 | 
        } 
 | 
    } 
 | 
} 
 |