- Get the desired start time for your task from a form:
String startTime = request.getParameter("startTime"); String startDate = request.getParameter("startDate"); //assume time is in HH:MM format, date is in MMDDYEAR format int startHour = Integer.parseInt(startTime.substring(0, 2)); int startMin = Integer.parseInt(startTime.substring(3, 5)); int startMonth = Integer.parseInt(startDate.substring(0, 2)); int startDate = Integer.parseInt(startDate.substring(2, 4)); int startYear = Integer.parseInt(startDate.substring(4, 8)); - Get a time zone:
Below are three approaches to get a Los Angeles time zone.- Method 1:
This is the simplest way. If you can not find a supported time zone suits you, you can use method 2.TimeZone timezone = TimeZone.getTimeZone("America/Los_Angeles"); - Method 2:
String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); SimpleTimeZone timezone = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
- Method 3:
SimpleTimeZone timezone = new SimpleTimeZone(-28800000, "America/Los_Angeles", Calendar.APRIL, 1, -Calendar.SUNDAY, 7200000, Calendar.OCTOBER, -1, Calendar.SUNDAY, 7200000, 3600000);
- Method 1:
- Get the sleep time for the thread by comparing two timestamps:
//get the timestamp for the start time set by users Calendar calendar = new GregorianCalendar(timezone); //the index values in the some parameters start from 0 calendar.set(startYear, startMonth - 1, startDate - 1, startHour - 1, startMin, 0); Timestamp ts = new Timestamp(calendar.getTimeInMillis()); long startTime = ts.getTime(); //get current timestamp Calendar calendarNow = new GregorianCalendar(tz); Timestamp tsNow = new Timestamp(calendarNow.getTimeInMillis()); long now = tsNow.getTime(); // there are 90000000 ms offset long sleepTime = startTime - now + 90000000;
- Finally, wake up the thread after specific time period.
try { if (sleepTime > 0) Thread.sleep(sleepTime); else{ System.out.println("Tasks are executing now..."); } //list of tasks } catch (InterruptedException e) { e.printStackTrace(); }
Reference:
- TimeZone Javadoc: http://download.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getAvailableIDs%28%29
- SimpleTimeZone Javadoc: http://download.oracle.com/javase/6/docs/api/java/util/SimpleTimeZone.html