Java的Timer和TimeTask灵活定时任务实战

1、Java Timer和TimerTask解析

  A-TimerTask 是实现Runnable接口的abstract类

   包含 state 状态 Virgin=0、Scheduled=1、Excuted=2、canceled=3 工4个状态

   long nextExecutionTimer 下一次执行任务的时间的毫秒数

   long period  重复任务的毫秒周期

   public boolean cancel() //取消任务

   public long scheduledExecutionTime() //获取最近一次执行的时间
B-TaskQueue,用于封装任务的队列(本质就是数组)控制任务的执行
       private TimerTask[] queue = new TimerTask[128];
   private int size = 0;
C-Timer,用于定时执行
Timer 类持有一个内部线程类 TimerThread
public void run() {
    try {
       mainLoop()
;
   } finally {
       
// Someone killed this Thread, behave as if Timer cancelled
       synchronized(queue) {
           
newTasksMayBeScheduled = false;
           queue.clear();  // Eliminate obsolete references
       }
   }
}
核心方法:
private void mainLoop() {
    while (true) {//
        try {
            TimerTask task;
            boolean taskFired;
            synchronized(queue) {
                // Wait for queue to become non-empty
                while (queue.isEmpty() && newTasksMayBeScheduled)
                    queue.wait();
                if (queue.isEmpty())
                    break; // Queue is empty and will forever remain; die

                // Queue nonempty; look at first evt and do the right thing
                long currentTime, executionTime;
                task = queue.getMin();
                synchronized(task.lock) {
                    if (task.state == TimerTask.) {
                        queue.removeMin();
                        continue;  // No action required, poll queue again
                    }
                    currentTime = System.();
                    executionTime = task.nextExecutionTime;
                    if (taskFired = (executionTime<=currentTime)) {
                        if (task.period == 0) { // Non-repeating, remove
                            queue.removeMin();
                            task.state = TimerTask.;
                        } else { // Repeating task, reschedule
                            queue.rescheduleMin(
                              task.period<0 ? currentTime   - task.period
                                            : executionTime + task.period);
                        }
                    }
                }
                if (!taskFired) // Task hasn't yet fired; wait
                    queue.wait(executionTime - currentTime);
            }
            if (taskFired)  // Task fired; run it, holding no locks
                task.run();
        } catch(InterruptedException e) {
        }
    }
}

2、Java 线程同步 concurrent、Lock、ReentrantLock

   略


3、代码:

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 定时随机Service
 * Created by Walter.Huang
 * on 2015/9/23.
 */
@Service
public class ThreadAutoRecommendService {
    private static final Logger = LoggerFactory.(ThreadAutoRecommendService.class);
    public static final long = 1800L;

    @Autowired
    private AnchorTiebaThreadRecommendMapper threadRecommendMapper;

    private Lock lock = new ReentrantLock();

    private long currentThreadId = 0L;
    private int autoUpdate = 0;
    private long intervalSeconds = ;//1800private Timer timer;

    
    public long getExecuteSeconds() {
        return intervalSeconds;
    }

    public int getAutoUpdate() {
        return autoUpdate;
    }


    private boolean validateAuto(){
       return autoUpdate == 1 && intervalSeconds > 0L;
    }


    /**
     * * @param autoUpdate
     * @param intervalSeconds
     */
    public void setAutoUpdate(int autoUpdate,long intervalSeconds) {
        if(lock.tryLock()){//try {
                this.autoUpdate = autoUpdate;
                this.intervalSeconds =intervalSeconds;
                setCurrentThreadId();
                stopTimer();

                if(validateAuto()) {
                    timer = new Timer();
                    timer.schedule(new RemindTask(), 0, intervalSeconds * 1000);//}
            }catch (Exception e){
                .error("setAutoUpdate error:", e);
            }finally{
                lock.unlock();
            }
        }
    }

    /**
     * */
    private void setCurrentThreadId(){
        if(currentThreadId == 0L) {
            List<AnchorTiebaThreadRecommend> threadRecommends = list(new AnchorTiebaThreadRecommend(), 1, 1);
            if (CollectionUtils.(threadRecommends)) {
                currentThreadId = threadRecommends.get(0).getThreadId();
            }
        }
    }


    /**
     * * @return
     */
    public List<AnchorTiebaThreadRecommend> list(AnchorTiebaThreadRecommend record, Integer curPage, Integer pageSize) {
        AnchorTiebaThreadRecommendExample example = buildExample(record);
        example.setLimit(pageSize);
        example.setOffset((curPage - 1) * pageSize);
        example.setOrderByClause("create_time desc");
        return threadRecommendMapper.selectByExample(example);
    }



    /**
     * * @param record
     * @return
     */
    public int getCount(AnchorTiebaThreadRecommend record) {
        AnchorTiebaThreadRecommendExample example = buildExample(record);
        return threadRecommendMapper.countByExample(example);
    }


    /**
     * * @return GroupsExample
     */
    private AnchorTiebaThreadRecommendExample buildExample(AnchorTiebaThreadRecommend record) {
        AnchorTiebaThreadRecommendExample example = new AnchorTiebaThreadRecommendExample();
        AnchorTiebaThreadRecommendExample.Criteria criteria = example.createCriteria();

        if(record.getThreadId() != null && record.getThreadId()>0){
            criteria.andThreadIdNotEqualTo(record.getThreadId()); //id,}
        criteria.andStateEqualTo(ThreadRecommendService.);//return example;
    }


    class RemindTask extends TimerTask{

        @Override
        public void run(){
            AnchorTiebaThreadRecommend recommend = new AnchorTiebaThreadRecommend();
            recommend.setThreadId(currentThreadId);//int count = getCount(recommend);
            if(count == 0){
                return;
            }

            int row = new Random().nextInt(count) + 1;//List<AnchorTiebaThreadRecommend> threadRecommends = list(recommend, row, 1);

            if(CollectionUtils.(threadRecommends)){
                recommend = threadRecommends.get(0);
                currentThreadId = recommend.getThreadId();

                recommend = new AnchorTiebaThreadRecommend();
                recommend.setThreadId(currentThreadId);
                recommend.setCreateTime(new Date());
                threadRecommendMapper.updateByPrimaryKeySelective(recommend);
            }
        }

    }


    /**
     * */
    private void stopTimer(){
        if(timer != null) {
            timer.cancel();
            timer = null;
        }
    }


}



你可能感兴趣的:(Java的Timer和TimeTask灵活定时任务实战)