zoukankan      html  css  js  c++  java
  • Timer 与 TimerTask 示例

    Java代码  收藏代码
    1. //任务  
    2. public class TaskSchedule extends TimerTask {  
    3.   
    4.                 //TimerTask 实现了 RUnnable 接口  
    5.     public void run() { //计划任务中具体做是事情  
    6.         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss.SSS");  
    7.         System.out.println(df.format(new Date()));  
    8.     }  
    9.   
    10. }  
    11.   
    12. //任务定时器  
    13. public class TimerSchedule {  
    14.   
    15.     public static void main(String[] args) throws InterruptedException {  
    16.         Timer timer = new Timer();  
    17.         timer.schedule(new TaskSchedule(), 10001000);// 1秒后执行 然后每隔1秒 执行一次  
    18.         Thread.sleep(5000);  
    19.         timer.purge();//释放 已经取消的任务所占用的内存  
    20.         System.out.println("purge mem of cancled task");  
    21.         Thread.sleep(5000);  
    22.         timer.cancel();//停止任务(程序停止)  
    23.     }  
    24.   
    25. }  


    /**
    * 启动刷新滚动数据的定时器
    */
    public void startRefreshTimer(int refreshInterval) {
    if (null == refreshTimer) refreshTimer = new Timer();
    refreshTimer.schedule(new TimerTask() {
    @Override
    public void run() {
    getScrollingMessage(false);
    }
    }, refreshInterval, refreshInterval);
    }


    Timer类中常用的方法:

    cancel()   终止计时器,并放弃所有已安排的任务,对当前正在执行的任务没有影响。

    purge()   将所有已经取消的任务移除,并释放移除任务的资源。

     

    schedule(TimerTask task, Date time)

                  在指定的 Date 运行任务,如果时间已经过了则立即执行任务

    schedule(TimerTask task, Date time, long period)

                  在指定的 Date 运行任务,当第一次运行后 每个 long 时间再运行

    schedule(TimerTask task, long delay)  

                  指定间隔时间运行

    schedule(TimerTask task, long delay, long period)  

                  指定间隔时间运行,并每隔period再运行,都是毫秒

     

    以下两个方法基本同上面相同,区别在于以下方法是按照 rate 比率 进行的,

    也就是接近于 period 的时间运行。方法可以根据出现的延迟时间自动调整下一次间隔的执行时间。

    而上面的四个方法则间隔永远是固定的。

    scheduleAtFixedRate(TimerTask task, Date firstTime, long period)

    scheduleAtFixedRate(TimerTask task, long delay, long period)







  • 相关阅读:
    鸟哥linux私房菜学习笔记,U盘安装centos5.3不能正常进入图形界面的问题
    loadrunner11的移动端性能测试之脚本录制
    JVM(java 虚拟机)内存设置
    数据结构一元多项式加减乘
    数据结构顺序表
    数据结构栈
    LoadIcon(nFaceID[i])
    数据结构单链表
    mysql得到wenshell
    窗口背景刷新的问题
  • 原文地址:https://www.cnblogs.com/jeffen/p/6640425.html
Copyright © 2011-2022 走看看