Java timer task: Adjusting daylight saving time

I have a piece of code that has to be executed at a particular time every day. If I schedule it to be executed at 9PM everyday, then it has to work even during the switching of Day light saving.

Which Java API can be used to achieve this?

int ONE_DAY = 1000 * 60 * 60 * 24;
Timer timer = new Timer();
timer.schedule(myTimerTask, startTime, ONE_DAY); // startTime is 9PM of current day

I've used the above approach which will not take care of DST.

Jon Skeet
people
quotationmark

If you need to schedule based on calendrical values - rather than just elapsed time, basically - then you either need to wrap Timer in your own code, or use a library which has already been built for this purpose. In this case, I suspect the Quartz Scheduler is your best bet.

Given how complicated date/time can be, I'd generally recommend using a well-known library over rolling your own code. Note that this often doesn't mean that you can get away without thinking about complicated aspects of the problem - it just means that you should be able to express your requirements fairly simply. For example, in the context you're looking at, you should consider:

  • What time zone do you want the "9pm" to be expressed in? Is it the system default time zone? Some other specific one? Multiple different time zones for different tasks?
  • What do you want to happen if the scheduled time doesn't occur, or occurs twice on one day? You're likely to be okay with 9pm, but if you had (say) 1.30am in the UK time zone, when the clocks go forward into BST, that will be skipped for that day - and when the clocks go back into GMT, it will occur twice.
  • How do you want to handle the system clock being changed, either manually or automatically?

people

See more on this question at Stackoverflow