Timer定时器

定时器的功能是定时做任务或者按一定事件间隔做任务。

1、schedule(TimerTask task, Date executeTime) executeTime时间之后做任务,代码如下:

new Timer().schedule(new TimerTask() {
	
	@Override
	public void run() {
		System.out.println("bombing!");
	}
}, 1000);
while(true) {
	System.out.println(new Date().getSeconds());
	try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

测试结果如下:

42
bombing!
43
44

2、schedule(TimerTask task, Date firstTime, long period)第一次firstTimer执行任务之后,以后每隔period时间执行一次任务,代码如下:

new Timer().schedule(new TimerTask() {
	
	@Override
	public void run() {
		System.out.println("bombing!");
	}
}, 1000,3000);
while(true) {
	System.out.println(new Date().getSeconds());
	try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

测试结果如下:

45
bombing!
46
47
48
bombing!
49
50
51
bombing!

有一个需求,比如每隔2秒和每隔4秒交替执行任务,需要自定义TimerTask类来执行任务,代码如下:

private static int count = 0;
class MyTimerTask extends TimerTask{
	@Override
	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();
	}
}

测试结果如下:

7
8
bombing!
9
10
11
12
bombing!
13
14
bombing!
15
16
17
18
bombing!

PS:若有需求周一至周五定时发邮件,周六日不发,可用quartz开源库来实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值