我想在java.null中编写一个定时器,它将执行以下操作: 程序启动时,启动定时器1,它将在45分钟后停止,同时启动第二个定时器,这将会在15分钟后停止。此时第一个定时器将再次启动,并重复上述循环,直到程序退出 第一个定时器:45分钟(我可以使用计算机的时间) 第二个定时器:15分钟(暂停时间) 第一个定时器:45分钟(时间我可以使用计算机) 第二定时器:15分钟(暂停时间) 第一定时器:45分钟(我可以使用计算机的时间) 第二定时器:15分钟(暂停时间)Java如何编写定时器
我不知道如何使用线程和定时器(utils,swing),所以我试图使用while(true),但CPU上升。 这里是我当前的代码
static int getMinute(){
Calendar cal=Calendar.getInstance();
int minute=cal.getTime().getMinutes();
return minute;
}
public static Runnable clockf(){
if (endTime>=60){
endTime=endTime-60;}
System.out.println(startTime);
System.out.println(currentTime);
System.out.println(endTime);
if(currentTime==endTime){
pauseStart=getMinute();
currentTime=getMinute();
pauseEnd=pauseStart+15;
if(currentTime==pauseEnd){
pauseStart=0;
pauseEnd=0;
startTime=getMinute();
currentTime=getMinute();
endTime=startTime+45;
}
}
else{
update();
}
return null;
}
private static void update() {
currentTime=getMinute();
System.out.println(currentTime);
}
public static void main(String[] args) {
startTime=getMinute();
currentTime=getMinute();
endTime=startTime+45;
Thread t=new Thread(clockf());
t.setDaemon(true);
t.start();
try {
Thread.currentThread().sleep(1000);//60000
} catch (InterruptedException e) {
System.err.println(e);
}
}
,但它不是很好。有没有办法让clockf方法只运行一次/分钟? 或任何其他方式来使该计时器运行?