likes
comments
collection
share

Java | 一分钟掌握定时任务 | 3 - 单机定时之Timer

作者站长头像
站长
· 阅读数 15

作者:Mars酱

声明:本文章由Mars酱原创,部分内容来源于网络,如有疑问请联系本人。

转载:欢迎转载,转载前先请联系我!

介绍

这个是个JDK远古时代的api了,据考证,可以追溯到JDK 1.3 的时候,历史就不讲了,毕竟我们不是技术考古。还是按照我们以前的方式,废话少说直接上车吧。

简单使用

我们先直接new一个Timer对象:

java.util.Timer timer = new Timer();

然后调用时,发现可用的方法并不多:

Java | 一分钟掌握定时任务 | 3 - 单机定时之Timer

根据多年算命经验,我猜既然是定时任务,那么包含关键字schedule的就是核心方法了,挑个最简单的写下来:

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author mars酱
 */
public class MarsTimer {
    public static void main(String[] args) {
        java.util.Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("当前时间:" + new Date());
            }
        }, 1000, 5000);
    }
}

运行了一下,得到了个结果:

Java | 一分钟掌握定时任务 | 3 - 单机定时之Timer

结果是每五秒执行一次输出。

Timer的schedule函数有三个参数:

TimerTask:这个就是需要安排的任务对象了,可以new一个之后像我一样实现它的run方法;

delay:在任务执行之前延迟多久,单位是毫秒;

period:每次执行之间的间隔多久,单位也是毫秒;

好了,就是这么简单,感觉再复杂也复杂不到哪里去了

会不会有阻塞?

我们理想的定时任务,应该是多个定时器同步并发执行,各自之间不受影响,对吧?那我们试试Timer会不会有这样的情况吧。

我们假设两个任务,一个任务在执行的过程中导致某些不可抗拒的原因,延迟了5秒,那么另一个任务的执行是不是会被这个延迟的任务影响,理想的情况下的两个定时任务各自完成自己任务,互不干涉和影响。

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author mars酱
 */
public class MarsTimer {
    public static void main(String[] args) {
//        java.util.Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                System.out.println("当前时间:" + new Date());
//            }
//        }, 1000, 5000);

        // 1. 创建第一个任务,打印时间后延迟5秒
        TimerTask tta = new TimerTask() {
            @SneakyThrows
            @Override
            public void run() {
                System.out.println(">> 这是a任务:当前时间:" + new Date());
                Thread.sleep(5000);
            }
        };

        // 2. 创建第二个任务,直接打印毫秒数
        TimerTask ttb = new TimerTask() {
            @Override
            public void run() {
                System.out.println("<< 这是b任务:当前毫秒:" + System.currentTimeMillis());
            }
        };

        Timer timera = new Timer();
        // 3. 把两个任务都加入计时器中
        timera.schedule(tta, 1000, 5000);
        timera.schedule(ttb, 1000, 5000);
    }
}

运行一下,得到结果:

Java | 一分钟掌握定时任务 | 3 - 单机定时之Timer

看出什么来了吗?是不是从结果中没看明白?我就知道,那么我们去掉那段Thread.sleep,得到的结果类似这样:

Java | 一分钟掌握定时任务 | 3 - 单机定时之Timer

对比一下上下两个结果,这下是不是明白了?由于a任务的延迟,导致了b任务受到了影响。看来JDK的定时任务是存在阻塞情况的,b任务执行只能等待a完成之后才能执行。

怎么解决?

先不解决,那是下一章节的内容,哈哈哈哈

其他方法

我们先介绍完Timer和TimerTask吧。

TimerTask是个抽象类,依赖Runnable接口,实现TimerTask,我们只要实现run函数就行了,就像这样:

import java.util.TimerTask;

/**
 * @author mars酱
 */
public class DefaultTimerTask extends TimerTask {
    @Override
    public void run() {
        // 你的业务实现
    }
}

原理

翻看java.util.Timer的源代码,核心点如下:

    /**
     * Schedule the specified timer task for execution at the specified
     * time with the specified period, in milliseconds.  If period is
     * positive, the task is scheduled for repeated execution; if period is
     * zero, the task is scheduled for one-time execution. Time is specified
     * in Date.getTime() format.  This method checks timer state, task state,
     * and initial execution time, but not period.
     *
     * @throws IllegalArgumentException if <tt>time</tt> is negative.
     * @throws IllegalStateException if task was already scheduled or
     *         cancelled, timer was cancelled, or timer thread terminated.
     * @throws NullPointerException if {@code task} is null
     */
    private void sched(TimerTask task, long time, long period) {
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");

        // Constrain value of period sufficiently to prevent numeric
        // overflow while still being effectively infinitely large.
        if (Math.abs(period) > (Long.MAX_VALUE >> 1))
            period >>= 1;

        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");

            synchronized(task.lock) {
                if (task.state != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }

            queue.add(task);
            if (queue.getMin() == task)
                queue.notify();
        }
    }

这段大致的意思就是往Timer内部的一个队列里面塞任务,塞的时候做了很多检查,比如周期、任务状态等等,用到了关键字synchronized,那么说明这个队列是个资源共享的,每次操作的时候必须一下,那么我们再看下Timer在执行队列的部分源代码:

    /**
     * The main timer loop.  (See class comment.)
     */
    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.CANCELLED) {
                            queue.removeMin();
                            continue;  // No action required, poll queue again
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTime<=currentTime)) {
                            if (task.period == 0) { // Non-repeating, remove
                                queue.removeMin();
                                task.state = TimerTask.EXECUTED;
                            } 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) {
            }
        }
    }

Timer在构造函数中就调用了start函数,start函数底层可以理解为用jvm去调用run函数,而这个mainLoop函数是Timer函数的实现部分,所以,最终Timer的执行都是在这里了。大致的执行顺序解释:

  1. 检查队列的情况,是不是空,是不是状态正常;
  2. 当前任务的状态是不是可以执行;
  3. 当前任务是不是已经到了可以触发的时间了
  4. 以上情况都ok,那就执行我们之前实现TimerTask的run函数

以上四点过程,全程都用synchronized包裹。

总结

Timer和TimerTask是JDK原生提供的定时任务实现方案,简单易用,但是平时的场景也经常会有业务处理过程较长的情况,但是单个任务的执行不能影响其他任务的定时情况,所以如果处理定时任务的并发,我们可以使用线程池,下个站见。

转载自:https://juejin.cn/post/7228071726205239353
评论
请登录