您的位置:首页 > 其它

传统定时器技术回顾

2014-05-28 16:47 351 查看
要求:创建定时器 隔2秒 做一次操作 隔4秒 做一次操作 隔2秒 做一次操作 隔4秒 做一次操作...一直循环下去

方法1:

package cn.cblue.heima2;

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

/**

* @Description: 创建定时器

* @author huangzjb cblue2013@126.com

* @Company Digital China

* @date 2014-5-28 下午04:35:00

* @version 1.0

*/

public class TraditionalTimerTest {

private 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);

while (true) {

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

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

方法2:

package cn.cblue.heima2;

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

/**

* @Description: 创建定时器 隔2秒 做一次操作 隔4秒 做一次操作 隔2秒 做一次操作 隔4秒 做一次操作...一直循环下去

* @author huangzjb cblue2013@126.com

* @Company Digital China

* @date 2014-5-28 下午04:43:34

* @version 1.0

*/

public class TraditionalTimerTest2 {

static class mytimertask1 extends TimerTask{

public void run() {

System.out.println("bombing");

new Timer().schedule(new mytimertask2(), 4000);

}

};

static class mytimertask2 extends TimerTask{

public void run() {

System.out.println("bombing");

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

}

};

public static void main(String[] args) {

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

while (true) {

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

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

tips:定时任务时间设置可以使用quartz框架来处理
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: