简体   繁体   中英

Schedule Task in java using Timer

I have created timezone specific schedule task event using java. My code is bellow.

Timer timer = new Timer();
Calendar date = Calendar.getInstance(TimeZone.getTimeZone("Asia/Colombo"));
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
timer.schedule(new TimerTask() {
    public void run() {
        System.out.println("Runs everday morning 12.00 AM");
    }
 }, date.getTime(), 1000 * 60 * 60 * 24);

But the problem is when call to this method it runs this task soon. I need to run this job 12.00 in Asia/Colombo time zone every day. How to do that?

You're scheduling your first execution in the past (midnight of the current day), and therefore your task will be executed immediately.

According to the javadoc :

[...] if the scheduled first time is in the past, it is scheduled for immediate execution.

The easiest way to fix this, is by adding 1 day to your scheduled first execution time:

date.add(Calendar.DATE, 1);

Additionally, you probably want to schedule the execution of this task as fixed rate instead of fixed delay . If you don't, your task will be executed a little bit later every day, depending on the actual time it takes to complete the task. Again, see the javadoc for details.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM