传统定时器技术-笔记整理2

定时器的应用

  参考:http://www.fx114.NET/qa-126-102338.aspx  

 

主要是了解定时器使用的技巧,使其间隔相同时间或不同时间一直执行下去,或者某个固定的时刻或日期,执行,有相关的插件可以实现。主要是当遇到问题的时候,想到有这样的解决方案

 

Timer:一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。

特有方法:

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

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

 

TimerTask: Timer 安排为一次执行或重复执行的任务。

boolean cancel();  取消此计时器任务

abstract void run();  此计时器任务要执行的操作。

 

示例代码:

 

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

 

public class TraditionalTimerTest {

public static void main(String[] args) {

Timer timer = new Timer();

timer.schedule(new TimerTask() {

@Override

public void run() {

// TODO Auto-generated method stub

System.out.println("bombing");

}

},10000);

new Timer().schedule(

new TimerTask(){

public void run(){

System.out.println("bombing");

}

},

10000,

3000);

/*

  //相隔相同的时间,运行定时器

public static void main(String[] args) {

class MyTimerTask extends TimerTask{

 public void run(){

 System.out.println("bombing");

  new Timer().schedule(new MyTimerTask(), 2000);

 }

}

new Timer().schedule(new MyTimerTask(), 2000);

}

 

*/

 

/*

//可以根据生成不同间隔的算法,使定时器一直按照不同的时间间隔执行下去

static int count=0;

public static void main(String[] args) {

class MyTimerTask extends TimerTask{

    public void run(){

 count = (count+1)%2;

 System.out.println("bombing");

  new Timer().schedule(new MyTimerTask(),2000+2000*count);

 

 }

new Timer().schedule(new MyTimerTask(), 2000);

}

*/

 

/*

//两秒之后,三秒之后再炸

new Timer().schedule(new TimerTask(){

   public void run(){

    System.out.println("bombing");

    new Timer().schedule(new TimerTask(){

 public void run(){

 System.out.println("bombing");

 }

 },

 3000);

   }

},

2000);

*/

while(true){

System.out.println(new Date().getSeconds());

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值