Quick question here, I need to execute a certain method only after a specific time period has passed (in milliseconds):
static double incrTrueBinaryErr = 62.5;
static double incrTrueBinaryMov = 31.25;
static double incr01001 = 360000;
static double incr_1101 = 125;
static double incr05008 = 3600000;
static double incr10004 = 1024000;
static double incr22000 = 1000;
static double incr22001 = 1000;
Date currDate;
while (true)
{
currDate = new Date();
if (currDate.getTime() == currDate.getTime() + incrTrueBinaryErr)
//do stuff
if (currDate.getTime() == currDate.getTime() + incrTrueBinaryMov)
//do stuff
if (currDate.getTime() == currDate.getTime() + incr01001)
//do stuff
if (currDate.getTime() == currDate.getTime() + incr_1101)
//do stuff
if (currDate.getTime() == currDate.getTime() + incr05008)
//do stuff
if (currDate.getTime() == currDate.getTime() + incr10004)
//do stuff
if (currDate.getTime() == currDate.getTime() + incr22000)
//do stuff
if (currDate.getTime() == currDate.getTime() + incr22001)
//do stuff
}
However, my program never hits any of these because of how specific the time intervals are.
What is the best way to go about doing this?
This kind of expression currDate.getTime() == currDate.getTime() + incr01001
will evaluate to true
only if incr01001 == 0
. For the same reason x == x + y
only when y == 0
.
To execute a certain method only after a specific time period has passed (in milliseconds):
You can use Thread.sleep(long milliseconds)
method to do that.
try{
Thread.sleep(5000);//for 5 seconds
} catch(Exception ex){
System.out.println("Error: "+ex.getMessage());
}
Try getting the time outside your while block first:
Date date = new Date();
while (true)
{
currDate = new Date();
if (currDate.getTime() == date.getTime() + incrTrueBinaryErr)
//do stuff
//etc.
}
This way the while loop doesn't keep reassigning the date.
It might also be a bit too specific as you say, so for your if
block maybe:
long timeDifference = date.getTime()+incrTrueBinaryErr-currDate.getTime();
if (Math.abs(timeDifference)<5l)
//do stuff
If the new time is within 5 milliseconds of what you want, "do stuff".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.