Reputation: 477
I was wondering if I could continually check for when today's is matched up with a date in the future. For instance if the date set in the future was 1/8/2015 and the date today was 1/7/2015. Is there a way to automatically keep checking when today's date becomes 1/8/2015 (matching with the date set in the future).
I was thinking about using a while(true) loop but it didn't feel right because the loop would never end. How else would I do this?
EDIT : So based off some online research and answer here I did this.
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.DAY_OF_MONTH, 1);
Date date = cal2.getTime();
System.out.print(cal2.getTime().toString());
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
for (int i = 1; i < 1000; i++) {
if (shelf.book[i] != null && shelf.book[i].overdue == true) {
}
}
}
}, date);
Note: I haven't tested it yet. (Also the run() method isn't done yet)
Upvotes: 2
Views: 1988
Reputation: 4111
For one time scheduling, an easy solution would be to use a Timer.
import java.util.*;
import java.text.*;
public class ScheduleTask {
private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static Timer timer = new Timer();
private static class MyTimeTask extends TimerTask {
public void run() {
System.out.println("HOHO date just changed");
}
}
public static void main(String[] args) throws ParseException {
System.out.println("Current Time: " + df.format( new Date()));
//Date and time at which you want to execute
Date date = df.parse("2015-01-08 00:00:00");
timer.schedule(new MyTimeTask(), date);
}
}
Upvotes: 3
Reputation: 2129
Busy waiting (aka polling) is generally a bad idea because it wastes resources. In this specific case there's no need to poll because you know the current datetime as well as the future datetime that you want to trigger on. Calculate the difference in time and use a timer to run your code at the necessary time. Java timer class
For example, let's say the current time is Jan 7 @4pm. You want to trigger on Jan 8 @12am. The time difference is 8 hours (28800 seconds or whatever unit of time you need to pass to the timer). Set a schedule for that duration and provide a callback function.
Upvotes: 2
Reputation: 53879
Instead of actively checking, use a ScheduledExecutorService
that executes a Runnable
in the future:
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
long delay = dateInFuture.getTime() - new Date().getTime();
ses.schedule(new Runnable(){
@Override
public void run() {
// do some work
}
}, delay, TimeUnit.MILLISECONDS);
Upvotes: 2