竹山一叶

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
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)







posted on 2017-03-29 16:28  竹山一叶  阅读(341)  评论(0编辑  收藏  举报