• 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()侧重执行频率的稳定,即便前一个线程没有执行完,而下一个线程到了该执行的时间,也会开始下一个线程

  • 相关阅读:
    listview侧滑删除
    从相册获取图片及调用相机拍照获取图片,最后上传图片到服务器
    Volley框架设置sessionid
    Android Studio关于SVN的相关配置及从SVN检出项目
    Android的Message Pool是什么——源码角度分析
    Handler.sendMessage 与 Handler.obtainMessage.sendToTarget比较
    Android Studio调试方法学习笔记
    textview设置drawable
    浅析:点击父控件时,子控件中的textview自动进入选中状态
    spring整合mongo及调用
  • 原文地址:https://www.cnblogs.com/shineyoung/p/10470778.html
Copyright © 2020-2023  润新知