Schedule a Java task in a specified time

I would like to be able to schedule a task at a specific time in Java. I understand that ExecutorService has the ability to schedule periodic intervals after a certain delay, but I'm looking for more time, not after the duration.

Is there a way to execute, say Runnable execute at 2:00, or do I need to calculate the time between 2:00 and 2:00, and then schedule the launch to run after this delay?

+4
source share
6 answers

You will need Quartz .

+3
source

you can also use spring annotations

 @Scheduled(cron="*/5 * * * * MON-FRI") public void doSomething() { // something that should execute on weekdays only } 

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

+5
source

this is how i solved it with java7SE:

  timer = new Timer("Timer", true); Calendar cr = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cr.setTimeInMillis(System.currentTimeMillis()); long day = TimeUnit.DAYS.toMillis(1); //Pay attention - Calendar.HOUR_OF_DAY for 24h day model //(Calendar.HOUR is 12h model, with pmam ) cr.set(Calendar.HOUR_OF_DAY, it.getHours()); cr.set(Calendar.MINUTE, it.getMinutes()); long delay = cr.getTimeInMillis() - System.currentTimeMillis(); //insurance for case then time of task is before time of schedule long adjustedDelay = (delay > 0 ? delay : day + delay); timer.scheduleAtFixedRate(new StartReportTimerTask(it), adjustedDelay, day); //you can use this schedule instead is sure your time is after current time //timer.scheduleAtFixedRate(new StartReportTimerTask(it), cr.getTime(), day); 

it is harder than I thought to do it right

+4
source

Got into this situation this morning ... It was my code to run at midnight

  scheduler = Executors.newScheduledThreadPool(1); Long midnight=LocalDateTime.now().until(LocalDate.now().plusDays(1).atStartOfDay(), ChronoUnit.MINUTES); scheduler.scheduleAtFixedRate(this, midnight, 1440, TimeUnit.MINUTES); 
+2
source

Check out the Quartz . We use it for our production applications, and this is very good. It is very similar to crontab. You can specify the time during the set schedule, and at that time he will make a callback.

0
source

user java.util.Timer . It has a new schedule(task, time) method, where time is the date you want to run the task once.

0
source

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


All Articles