import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; public class JavaTimerExample { public static void main(String[] args) { Calendar calendar = getCalendar(16, 29); System.out.println("date : " + calendar.getTime()); Timer timer = new Timer(); // Instantiate Timer Object timer.schedule(new CustomTask(), calendar.getTime(), TimeUnit.SECONDS.toMillis(10)); } private static class CustomTask extends TimerTask{ private Date endDate; @SuppressWarnings("deprecation") public CustomTask() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MINUTE, cal.getTime().getMinutes() + 2); this.endDate = cal.getTime(); } public CustomTask(int endDay, int endHour, int endMinute) { Date date = getCalendar(endDay, endHour, endMinute).getTime(); this.endDate = date; } @Override public void run() { Date now = new Date(); System.out.println("hello custom task, time is + " + now); if(now.after(endDate)) { cancel(); Thread.currentThread().interrupt(); } } } public static Calendar getCalendar(int hour, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set( Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY ); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } public static Calendar getCalendar(int day, int hour, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set( Calendar.DAY_OF_WEEK, day ); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } }