package com.my.timer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
public static void main(String[] args) {
//simpleTimerTest();//测试timer
alarmClock();//闹铃
}
//延迟3秒执行,并且每5秒执行一次
public static void simpleTimerTest() {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE)+":"+Calendar.getInstance().get(Calendar.SECOND));
}
}, 3000,5000);
}
//模拟一个午休闹铃,默认每五分钟响一次,响三次后闹钟结束
static int count=3,i=0;
public static void alarmClock(){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//响铃时间
Date taskDate=new Date();
//间隔周期
final long PERIOD=1000*60*5;
//默认响铃3次
try {
taskDate=sdf.parse("2014-07-01 13:54:10");
} catch (ParseException e) {
e.printStackTrace();
}
final Timer timer=new Timer();
TimerTask task=new TimerTask() {
@Override
public void run() {
if(i<count){
System.out.println("闹铃:"+new Date());
}else {
System.out.println("已响铃"+(i)+"次");
timer.cancel();
}
++i;
}
};
timer.schedule(task, taskDate, PERIOD);
}
}
以上代码复制可用
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
public static void main(String[] args) {
//simpleTimerTest();//测试timer
alarmClock();//闹铃
}
//延迟3秒执行,并且每5秒执行一次
public static void simpleTimerTest() {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+":"+Calendar.getInstance().get(Calendar.MINUTE)+":"+Calendar.getInstance().get(Calendar.SECOND));
}
}, 3000,5000);
}
//模拟一个午休闹铃,默认每五分钟响一次,响三次后闹钟结束
static int count=3,i=0;
public static void alarmClock(){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//响铃时间
Date taskDate=new Date();
//间隔周期
final long PERIOD=1000*60*5;
//默认响铃3次
try {
taskDate=sdf.parse("2014-07-01 13:54:10");
} catch (ParseException e) {
e.printStackTrace();
}
final Timer timer=new Timer();
TimerTask task=new TimerTask() {
@Override
public void run() {
if(i<count){
System.out.println("闹铃:"+new Date());
}else {
System.out.println("已响铃"+(i)+"次");
timer.cancel();
}
++i;
}
};
timer.schedule(task, taskDate, PERIOD);
}
}
以上代码复制可用