How to set the time?

Suppose I want to start a thread at a certain time, at the time I want, how can I set the time in the lower code so that I can start a thread at a certain time and after the same thread will support execution after a given time interval. (in the code example, suppose I want to run a beeper at midnight, how can I do this?

class BeeperControl { private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public void beepForAnHour() { final Runnable beeper = new Runnable() { public void run() { System.out.println("beep"); } }; final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); scheduler.schedule(new Runnable() { public void run() { beeperHandle.cancel(true); } }, 60 * 60, SECONDS); } } 

Thanks in advance.

+4
source share
3 answers

If you want to run the beeper after midnight, you need to change the initialDelay , which you will pass to the scheduler. Determine how much delay you need by subtracting the current time from midnight. This is shown below:

 private static Date getMidnight(){ Calendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH,1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); return cal.getTime(); } long initialDelay = (getMidnight().getTime() - System.currentTimeMillis())/1000; final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, initialDelay, 10, SECONDS); 
+1
source

Take a look at the Timer and TimerTask classes.

For advanced scheduling tasks, check out the Quartz Task Scheduler .

+6
source

Plan it initially by checking the difference between the current time and when you want to start the task. Then use scheduleAtFixedRate .. However, be careful, the thread does not have to be scheduled at the right time.

0
source

Source: https://habr.com/ru/post/1335806/


All Articles