Need to fix Java Timer code

Task. Turn on and off the lamp at the specified time during the day. I need to know how to fix my code according to the information below. I also need to know if I am using the timer class correctly, i.e. is my code working correctly? The code may work, but it may be a bad design that will cause problems later. I do not want this to happen.

Exit (this is not the result that I really wanted :() -

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 

The required conclusion is

 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. 

How to fix the code below to get what I want?

Bulb Class

 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 which is a 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 class - this is the schedule when the bulb is on or off.

 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
source share
4 answers

This section:

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

sets only one task. If you need to schedule it twice, do it explicitly:

 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 

Besides. this line:

 bj.setBulbStateEqualTo(false); 

runs in the main thread, so it will be in front of both tasks. You must schedule this statement to run between two tasks.

+2
source

The code is fixed, but this version cannot exit main at the end -

 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"); } } 
0
source

You are not setting the time correctly. Must use GreogarianCalendar.

java.util.Date is used but cannot use its setSeconds. Read the Javadoc, this is pretty good and will help a lot. public void setSeconds (int seconds)

Outdated. Starting with JDK version 1.1, Calendar.set (Calendar.SECOND, int seconds) is replaced. Sets the seconds of this date to the specified value. This Date object is modified so that it represents a point in time during the specified second of a minute, and the year, month, date, hour, and minute are the same as before, as interpreted in the local time zone.

You need to use java.util.GregorianCalendar # add (Calendar.SECOND, howManySeconds)

then use getDate () to get the Date object and send it to the timer.

calling setSecond on a date will not change the other fields. see java document Calendar.add and roll. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html and see the rules in the inro class.

0
source

You can also use the schedule of the timer object (TimerTask task, long delay) Runs the specified task to execute after the specified delay (milliseconds). Modified Code -

 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 } } 

Modified by BulbJob

import java.util. *;

the BulbJob class extends 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 } 

}

Class Bulb ... public void setState (logical state) {this.state = state; System.out.println ("Bulb" + name + "is" + (state? "On": "off") + "at" + BulbScheduler.formatDate (new java.util.Date ())); // if good too

}

0
source

All Articles