java自带定时任务功能(Timer&TimerTask)

java自带定时任务功能(Timer&TimerTask)


介绍

开发中我们经常会有这样的业务,比如在凌晨的时候跑一个任务或者指定在某个时刻跑任务,这就是所谓的定时任务。通常定时任务也是异步处理的,
此时我会联想到消息中间件的功能(异步与解耦),java自带了简单的定时任务功能,通过借助Timer和TimeTask可以时间简单的任务调度功能。


任务调度器的最核心两点
1、任务(定义具体干什么,通常实现Runnable接口)
2、调度器(定义何时如何调度任务)

java自带的简单任务调度无法满足企业开发应用,如果要实现比较复杂的任务调度那么就需要借助第三方组件比如Quartz。

通常实际开发我们会结合Quartz和Spring来达到我们任务调度的目的

Timer

java.util.Timer是一个实用工具类,该类用来调度一个线程,使它可以在将来某一时刻执行。 Java的Timer类可以调度一个任务运行一次,或定期运行。

说简单点Timer就是一个调度器。

Timer使用

/**
 * @author xuyi3
 * @2016年7月22日 @上午11:41:47
 * @TimeTest
 * @功能说明:<br>
 * @春风十里不如你
 * @备注
 */
public class TimerTest {

    //TImer构造方法演示
    public void testTimer() {

        // Timer timer=new Timer();//无参构造器
        // Timer timer=new Timer("timerName");//Creates a new timer whose
        // associated thread has the specified name(给运行这个Timer的线程命名)
        // Timer timer=new Timer(true);//指定运行这个Timer线程是否守护线程
        // Timer timer=new Timer("timerName", false);//命令和指定线程类型

    }

    /**
     * 凡是涉及到线程相关的内容学习,主要是在main方法里面跑,不要再Junit单元测试里面跑。
     * 
     * @param args
     */
    public static void main(String[] args) {

        Timer timer = new Timer();
        // 实际任务
        SimpleTimeTask simpleTimeTask = new SimpleTimeTask();

        // 延期时间
        long delayTime = 5000;
        // 执行周期
        long periodTime = 3000;

        /**
         * delayTime毫秒后开始执行任务
         */
        // timer.schedule(simpleTimeTask, delayTime);

        /**
         * delayTime毫秒之后开始执行任务,之后每隔periodTime执行一次。
         */
        // timer.schedule(simpleTimeTask, delayTime,periodTime);

        /**
         * Schedules the specified task for execution at the specified time. If
         * the time is in the past, the task is scheduled for immediate
         * execution.
         * 
         * 在指定时间执行任务,如果指定时间小于当前时间那么就立即执行
         * 
         */
        // timer.schedule(simpleTimeTask, new Date(System.currentTimeMillis() -
        // delayTime));

        /**
         * Schedules the specified task for repeated fixed-delay execution,
         * beginning after the specified delay. Subsequent executions take place
         * at approximately regular intervals separated by the specified period.
         * 
         * 
         * 在指定的延时后执行任务,之后每隔periodTime毫秒重复执行。
         * 
         * 和schedule(TimerTask task, long delay, long period)方法一样,只是策略有点不同
         * 
         */
        // timer.schedule(simpleTimeTask, new Date(), periodTime);

        // timer.scheduleAtFixedRate(simpleTimeTask, delayTime, periodTime);

        /**
         * Schedules the specified task for repeated fixed-rate execution,
         * beginning at the specified time. Subsequent executions take place at
         * approximately regular intervals, separated by the specified period.
         * 
         * 在指定的时间执行任务,之后每隔periodTime毫秒重复执行。
         * 
         * 和schedule(TimerTask task, Date firstTime, long period)方法一样,只是策略有点不同
         * 
         */
        // timer.scheduleAtFixedRate(simpleTimeTask, new Date(), periodTime);

        // 备注:策略(默认使用fixedDelay)
        // fixedRate:定时间隔执行,不管上次任务是否已执行完毕
        // fixedDelay:每次任务执行完毕之后delay固定的时间

    }

}

TimerTask类介绍和使用

TimerTask抽象类表示定义任务类,具体的任务都要继承该抽象类,该抽象类厘米那最主要的方法就是run()抽象方法。

代码

/**
 * A task that can be scheduled for one-time or repeated execution by a Timer.
 *
 * @author  Josh Bloch
 * @see     Timer
 * @since   1.3
 */

public abstract class TimerTask implements Runnable {
    /**
     * This object is used to control access to the TimerTask internals.
     */
    final Object lock = new Object();

    /**
     * The state of this task, chosen from the constants below.
     */
    int state = VIRGIN;

    /**
     * This task has not yet been scheduled.
     */
    static final int VIRGIN = 0;

    /**
     * This task is scheduled for execution.  If it is a non-repeating task,
     * it has not yet been executed.
     */
    static final int SCHEDULED   = 1;

    /**
     * This non-repeating task has already executed (or is currently
     * executing) and has not been cancelled.
     */
    static final int EXECUTED    = 2;

    /**
     * This task has been cancelled (with a call to TimerTask.cancel).
     */
    static final int CANCELLED   = 3;

    long nextExecutionTime;

    /**
     * Period in milliseconds for repeating tasks.  A positive value indicates
     * fixed-rate execution.  A negative value indicates fixed-delay execution.
     * A value of 0 indicates a non-repeating task.
     */
    long period = 0;


    /**
     * The action to be performed by this timer task.
     */
    public abstract void run();

    /**
     * Cancels this timer task.  If the task has been scheduled for one-time
     * execution and has not yet run, or has not yet been scheduled, it will
     * never run.  If the task has been scheduled for repeated execution, it
     * will never run again.  (If the task is running when this call occurs,
     * the task will run to completion, but will never run again.)
     */
    public boolean cancel() {
        synchronized(lock) {
            boolean result = (state == SCHEDULED);
            state = CANCELLED;
            return result;
        }
    }

    /**
     * Returns the scheduled execution time of the most recent
     * actual execution of this task.  (If this method is invoked
     * while task execution is in progress, the return value is the scheduled
     * execution time of the ongoing task execution.)
     */
    public long scheduledExecutionTime() {
        synchronized(lock) {
            return (period < 0 ? nextExecutionTime + period
                               : nextExecutionTime - period);
        }
    }
}

总结

如果是简单的定时任务设置,则可以使用java自带的TImer和TimerTask来完成,如果比较复杂的推荐使用Quartz任务调度框架来完成。

参考

1、http://www.importnew.com/9978.html
2、http://www.cnblogs.com/dolphin0520/p/3938991.html

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值