需要修复我的Java Timer代码

时间:2013-03-11 08:16:12

标签: java timertask

任务 - 在一天中的指定时间打开和关闭灯泡。我需要知道如何根据下面给出的信息修复我的代码。我还需要知道我是否正确使用了计时器类,也就是说,我的代码设计是否正确?代码可能有用,但可能是糟糕的设计,以后会引起问题。我不希望这种情况发生。

输出是(这不是我真正想要的输出:() -

This is the main program
Current time is - xxx
Future time is - xxx+5sec
Future time is - xxx+10sec
Main program ends
Bulb B1 is OFF

期望的输出 -

This is the main program
Current time is - xxx
Future time is - xxx+5sec
Future time is - xxx+10sec
Bulb B1 is ON  //first on
Bulb B1 is OFF //then off
Main program ends//This should always be in the end.

如何修复下面的代码以获得我想要的内容?

Bulb班级

class Bulb {

private boolean state = false;//On or off
private String name;

Bulb(String name){

    this.name = name;

}

public void setState(boolean state){

    this.state = state;
    if(this.state == true){

        System.out.println("Bulb " + name + " is ON");

    }else{

        System.out.println("Bulb " + name + " is OFF");

    }

}


public boolean getState(){
    return this.state;

}


}

BulbJob类是TimerTask

import java.util.*;

class BulbJob extends TimerTask{

private Bulb bulbToHandle;
private boolean setBulbStateEqualTo;

BulbJob(Bulb toHandle){

    this.bulbToHandle = toHandle;

}


//NOTE: Must be called before run(), otherwise default value is used
public void setBulbStateEqualTo(boolean setBulbStateEqualTo){

    this.setBulbStateEqualTo = setBulbStateEqualTo;

}


//NOTE: call run() only before calling above method
public void run(){

    this.bulbToHandle.setState(setBulbStateEqualTo);//Set on or off

}

}

BulbScheduler课程 - 当灯泡打开或关闭时,这会安排。

import java.util.*;

@SuppressWarnings( "deprecation" )
class BulbScheduler {

public static void main(String args[]) throws InterruptedException{

    System.out.println("This is the main program");

    Timer time = new Timer();
    Bulb b1 = new Bulb("B1");
    BulbJob bj = new BulbJob(b1);

    bj.setBulbStateEqualTo(true);//Task - Turn bulb on at time = afterCurrent

    Date current = new Date();//Get current time and execute job ten seconds after this time
    Date afterCurrent = (Date) current.clone();

    System.out.println("Current time is - " + current);

    int currentSecs = current.getSeconds();
    int offset = 5;//number of seconds

    afterCurrent.setSeconds(currentSecs + offset);
    System.out.println("Future time is - " + afterCurrent);

    time.schedule(bj, afterCurrent);//Schedule job "bj" at time = afterCurrent

    //Now turn the bulb off at new time = newest afterTime
    afterCurrent.setSeconds(currentSecs + 2 * offset);
    System.out.println("Future time is - " + afterCurrent);

    bj.setBulbStateEqualTo(false);//Task - Now turn the bulb off at time = afterCurrent

    System.out.println("Main program ends");

}

}

4 个答案:

答案 0 :(得分:2)

本节:

time.schedule(bj, afterCurrent);//Schedule job "bj" at time = afterCurrent

//Now turn the bulb off at new time = newest afterTime
afterCurrent.setSeconds(currentSecs + 2 * offset);

仅安排一项任务。如果您需要安排两次,请明确这样做:

time.schedule(bj, afterCurrent);//Schedule job "bj" at time = afterCurrent

//Now turn the bulb off at new time = newest afterTime
afterCurrent.setSeconds(currentSecs + 2 * offset);
time.schedule(bj, afterCurrent);//Schedule job "bj" at time = afterCurrent

另外。这一行:

bj.setBulbStateEqualTo(false);

在主线程中执行,因此它将在两个任务之前执行。您应该安排该语句在两个任务之间运行。

答案 1 :(得分:0)

代码已修复,但此版本最终无法退出main -

import java.util.*;

@SuppressWarnings( "deprecation" )
class BulbScheduler {

public static void main(String args[]) throws InterruptedException{

    System.out.println("This is the main program");

    Timer timeOn = new Timer();
    Timer timeOff = new Timer();
    Bulb b1 = new Bulb("B1");
    BulbJob bjOn = new BulbJob(b1);
    BulbJob bjOff = new BulbJob(b1);

    bjOn.setBulbStateEqualTo(true);//Task - Turn bulb on 
    bjOff.setBulbStateEqualTo(false);//Task - Then turn the bulb off later

    Date current = new Date();//Get current time and execute job ten seconds after this time
    Date afterCurrent = (Date) current.clone();

    System.out.println("Current time is - " + current);

    int currentSecs = current.getSeconds();
    int offset = 3;//number of seconds

    afterCurrent.setSeconds(currentSecs + offset);
    System.out.println("Future time is - " + afterCurrent);

    timeOn.schedule(bjOn, afterCurrent);//Schedule job "bj" at time = afterCurrent

    //Now turn the bulb off at new time = latest afterCurrent
    afterCurrent.setSeconds(currentSecs + 2 * offset);
    System.out.println("Future time is - " + afterCurrent);

    timeOff.schedule(bjOff, afterCurrent);

    System.out.println("Main program ends");

}

}

答案 2 :(得分:0)

您没有正确设置时间。需要使用GreogarianCalendar。

使用java.util.Date但不能使用它的setSeconds读取它非常好的Javadoc并且会帮助很多。 public void setSeconds(int seconds)

已过时。从JDK 1.1版开始,由Calendar.set(Calendar.SECOND,int seconds)取代。 将此Date的秒数设置为指定的值。修改此Date对象,使其表示指定的分钟秒内的时间点,年,月,日,小时和分钟与之前相同,如本地时区所解释。

你需要使用java.util.GregorianCalendar #add(Calendar.SECOND,howManySeconds)

然后使用getDate()获取Date对象并将其发送到Timer。

在日期上调用setSecond不会更改其他字段。查看Calendar.add和roll的java文档。 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html并查看课堂内的规则。

答案 3 :(得分:0)

还可以使用timer对象的schedule(TimerTask任务,长延迟) 在指定的延迟(毫秒)后安排指定的任务执行。 修改后的代码 -

import java.util.*;

class BulbScheduler {

    private static java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat ("yy MM dd HH mm ss");

//helper    
static String formatDate(Date d){
        return sdf1.format(d);
    }

    public static void main(String args[]) throws InterruptedException{
        System.out.println("This is the main method");
        java.util.GregorianCalendar cal = new java.util.GregorianCalendar();

        Bulb b1 = new Bulb("bulb 1", false);
        Bulb b2 = new Bulb("bulb 2", false);

        System.out.println("Time now " + formatDate(cal.getTime()));

        Timer timer = new Timer("bulbs");
        BulbJob b1On = new BulbJob(b1, true);
        BulbJob b1Off = new BulbJob(b1, false);
        BulbJob b2On = new BulbJob(b2, true);
        BulbJob b2Off = new BulbJob(b2, false);
        timer.schedule(b1On, 3 * 1000);//after 3 seconds
        timer.schedule(b2On, 7 * 1000);//after 4 seconds
        timer.schedule(b1Off, 6 * 1000);//after 6 seconds; before b2 on

        b1On = new BulbJob(b1, true);
        timer.schedule(b1On, 9 * 1000);


        //if you want main to wait need to add code here to make it wait,
        // but even if does the JVM wont exit. Its just a method. The JVM exits when all non daemon threads are done
        // or System.exit is called

        System.out.println("This is the main method ending; but other threads might be running ...");
        //main thread JVM waits for all other non dameons to end

    }

}

更改了BulbJob

import java.util。*;

类BulbJob扩展了TimerTask {

private Bulb bulbToHandle;
private boolean bulbNewState;//dont start propert names with set

//why a seperate property when we need to set the new state everytime and cannot reuse jobs?
BulbJob(Bulb toHandle, boolean newState){
    this.bulbToHandle = toHandle;
    bulbNewState= newState;
}

public void run(){
    this.bulbToHandle.setState(bulbNewState);//Set on or off
}

}

类灯泡...... public void setState(boolean state){     this.state = state;     System.out.println(“Bulb”+ name +“is”+(state?“on”:“off”)+“at”+ BulbScheduler.formatDate(new java.util.Date())); // if好吧

}