i am looking forward to learn java. I made this program , so that when the current date matches the specified date, it will execute some code, in this case, it will exit the while loop. I'd like to know if there any other ways, but for now i will stick with this string comparison.
For somewhat reasons the If loop isn't working properly, i monitor the current date with System.out.println(date) but when it reaches the desired date (by format HH:MM:SS) to do the action,the strings aren't equal and the while loop continues, is there anything i miss?
EDIT: Platform = windows 7
public class Main {
static String DesiredDate;
static String date;
static boolean Programisrunning;
public static void main(String[] args) {
DesiredDate = "17:24:10";
while(Programisrunning = true) {
date = CurrentDate.GetDate();
System.out.println(date);
if(date.equals(DesiredDate)) {
Programisrunning = false;
}
}
System.out.println("Program succesfully terminated");
}
}
//another class
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CurrentDate {
public static String GetDate(){
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
}
You can just use the Timer class to do time:
Or a repeating timer:
the Timer class also has a schedule(TimerTask, Date) method to execute a Date instead of a length of time (in milliseconds)
You can also look at a library I have written to help with java io and timer functions called "Shared Packages" which has a range of timers: https://github.com/JD9999/Shared-Packages/tree/master/Timers
Executors
While loop solution is bad because CPU is busy. Use executors, specifically
ScheduledExecutorService
.For calculations you should convert the text based date "hh:mm" in a long value, which represents the number of millis seconds sicne 1.1.1970 (UTC).
This value, e.g is delivered by System.currentTimeMillis();
The
SimpleDateFormat
will deliver the Date from a given formated human readable time (yyyy hh:mm:ss), too, the long value, can be get withdate.getTime()
;With that background use the class
ScheduledExecutorService
to run a task at given time.To schedule a task, use a
ScheduledExecutorService
: