| Author |
Need to compare date time in GMT
|
Sankar Ramakrishnan
Greenhorn
Joined: Aug 09, 2005
Posts: 4
|
|
Hi, I need to run a thread every 4 hours from GMT. This application can run from any Time zone (thats why GMT is preferred.) When the application starts i can do the processing and i need to set the sleep value of the thread. i am not able to to calculate the remaining milliseconds from the current time to the next scheduled time in GMT so that i can make set the thread to sleep for that particulcar period of time. Please help. Thanks, Sankar
|
 |
Phil Johnston
Greenhorn
Joined: Jul 25, 2005
Posts: 6
|
|
Not sure if it's what you're after but: package com; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.Timer; import java.util.TimerTask; /** * Created by IntelliJ IDEA. * User: Phil Johnston * Date: 09-Aug-2005 * Time: 20:22:37 */ public class TestTimer { private static TimeZone GMT = TimeZone.getTimeZone("GMT"); private static int DELAY = 1000*60*60*4; public static void main(String[] args) { Timer t = new Timer(); TimerTask task = new LocalTimerTask(); Calendar midnight = GregorianCalendar.getInstance(GMT); midnight.set(2005, 8, 10, 0, 0, 0); t.scheduleAtFixedRate(task, midnight.getTime(), DELAY); } private static class LocalTimerTask extends TimerTask { public void run() { // do my stuff } } }
|
 |
Sankar Ramakrishnan
Greenhorn
Joined: Aug 09, 2005
Posts: 4
|
|
Thanks dude, One small issue is it gets executed for the elapsed time. I need to schedule every 4 hrs from GMT. but it should not execute for elapsed values. i.e If i start the exe at 9 AM GMT, it should run next time at 12 PM GMT, not 2 times for 4 AM and 8 AM GMT. Hope i am clear. Regards, Sankar
|
 |
Sankar Ramakrishnan
Greenhorn
Joined: Aug 09, 2005
Posts: 4
|
|
This is the method i wrote to get the no of milliseconds remaining to reach the next scheduled task. private long getSleepInterval(int repeatHours) { Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar newCal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); newCal.set(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DATE),0,0,0); int maxLength = 24/repeatHours + 1; long[] timeinMilliSeconds = new long[maxLength]; long timeinMillis = cal.getTime().getTime(); timeinMilliSeconds[0] = newCal.getTime().getTime(); if(timeinMilliSeconds[0] > timeinMillis) return (timeinMilliSeconds[0] - timeinMillis); for (int i = 1;i < maxLength ;i++ ) { newCal.add(Calendar.HOUR_OF_DAY,repeatHours); timeinMilliSeconds[i] = newCal.getTime().getTime(); if(timeinMilliSeconds[i] > timeinMillis) return (timeinMilliSeconds[i] - timeinMillis); } return 0; }
|
 |
 |
|
|
subject: Need to compare date time in GMT
|
|
|