zoukankan      html  css  js  c++  java
  • Java Timer

    Java Timer 定时类,主要用来执行定时任务

    Timer管理所有要执行的定时任务

    TimerTask封装好的定时任务

    常见的用法

    MyTask myTask = new MyTask();
    Timer timer = new Timer();
    timer.schedule(myTask, new Date(), 1000);
    void schedule​(TimerTask task, long delay)
    Schedules the specified task for execution after the specified delay.
    void schedule​(TimerTask task, long delay, long period)
    Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
    void schedule​(TimerTask task, Date time)
    Schedules the specified task for execution at the specified time.
    void schedule​(TimerTask task, Date firstTime, long period)
    Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.
    void scheduleAtFixedRate​(TimerTask task, long delay, long period)
    Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
    void scheduleAtFixedRate​(TimerTask task,Date firstTime, long period)
    Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

    摘自jdk,简单概括一下

    schedule(TimerTask task, Date time):安排在指定的时间执行指定的任务。

    schedule(TimerTask task, Date firstTime, long period) :安排指定的任务在指定的时间开始进行重复的固定延迟执行。

    schedule(TimerTask task, long delay) :安排在指定延迟后执行指定的任务。

    schedule(TimerTask task, long delay, long period) :安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。

    scheduleAtFixedRate(TimerTask task, Date firstTime, long period):安排指定的任务在指定的时间开始进行重复的固定速率执行。

    scheduleAtFixedRate(TimerTask task, long delay, long period):安排指定的任务在指定的延迟后开始进行重复的固定速率执行。

    cancel()取消所有定时任务

    再来看下TimerTask

    Modifier and TypeMethodDescription
    boolean cancel()
    Cancels this timer task.
    abstract void run()
    The action to be performed by this timer task.
    long scheduledExecutionTime()
    Returns the scheduled execution time of the most recent actual execution of this task.

    只有run()是抽象方法,需要重写

    cancel()表示取消该定时任务

    scheduledExecutionTime()表示最近的定时任务的实际执行时间

    schedule()有个缺点,如果之前的线程花费时间较长,那么相应的之后的线程的执行时间也会相应延长

    scheduleAtFixedRate()可以避免上述问题,schedule()侧重时间间隔的稳定,而scheduleAtFixedRate()侧重执行频率的稳定,即便前一个线程没有执行完,而下一个线程到了该执行的时间,也会开始下一个线程

  • 相关阅读:
    ‘==’运算符和equals方法的区别
    ‘==’与equals的使用
    重写equals()方法的原则
    三目运算符---自动转换数据类型
    Spring安全框架——细粒度权限控制实现步骤
    Http协议学习笔记---Http协议介绍、协议格式、响应码说明
    Xml&Tomcat学习笔记03-----javaweb介绍、Tomcat介绍和使用
    Xml&Tomcat学习笔记02-----IDEA配置TomCat服务器
    Xml&Tomcat学习笔记01-----XML简介、语法、元素、属性、dom4j
    MVC概念
  • 原文地址:https://www.cnblogs.com/shineyoung/p/10470778.html
Copyright © 2011-2022 走看看