2

I have a code that has to be executed at a certain date time in the future, let's say that I have a future date and I want to execute a peace of code in that date +1 minute in the future, but only once. I know I to do this with a java Timer and TimerTask .For example doing something like this:

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Main {

    public static void main(String[] args) {

        Calendar myDate = Calendar.getInstance();
        myDate.add(Calendar.MINUTE, 1);
        Date afterOneMinute = myDate.getTime();
        System.out.println("Scheduled at:" + afterOneMinute);
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("Executed at:" + (new Date()));

            }
        }, afterOneMinute);
    }

}

I'm looking for an elegant way to to the same using ScheduledExecutorService, in order to have a specific pool, because this pool will be used for multiple calls. Does somebody can help me?

navy1978
  • 1,411
  • 1
  • 15
  • 35
  • What have you tried? What is the concrete problem? – JB Nizet Jun 17 '18 at 15:48
  • No problems at all, I want just to do the same thing in a different way (using ScheduledExecutorService), because I would like to use the pool in order to restrict the number of calls with a pool – navy1978 Jun 17 '18 at 15:49
  • So, read the javadoc of ScheduledExecutorService, and try something based on what you learn from reading the documentation. – JB Nizet Jun 17 '18 at 15:50
  • I have already done it , thank you, but I cannot find a way to execute it only once! It is written in my question! – navy1978 Jun 17 '18 at 15:51
  • Possible duplicate of [How to run certain task every day at a particular time using ScheduledExecutorService?](https://stackoverflow.com/questions/20387881/how-to-run-certain-task-every-day-at-a-particular-time-using-scheduledexecutorse) – Jacob G. Jun 17 '18 at 15:53
  • Well, https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html#schedule-java.lang.Runnable-long-java.util.concurrent.TimeUnit- says: Creates and executes a **one-shot** action that becomes enabled after the given delay. And even if you're still unsure after reading that, you can always try. – JB Nizet Jun 17 '18 at 15:57
  • Ok As explained in a comment below I didn't see it, and I was expecting to find a Date in the parameters of the methods, and in any case I was looking in the ScheduleAtFixedRate and there I could not find a one-shot execution... In any case I come here and I lost time to write a question, I don't thing your answers helped a lot... At least not the first 2, in any case Thank you... – navy1978 Jun 17 '18 at 16:04
  • 1
    @navy1978 when I told you to read the javadoc, I meant it. Not just vaguely look at it, and make incorrect assumptions. **read** it. There are 4 methods, and the two first ones do what you want to do. It's not that hard. Don't blame me for not correctly reading the javadoc, and for not doing it when I tell you to do it. – JB Nizet Jun 17 '18 at 16:10
  • I’m appreciating your explanation, but I really hate the answers like “read the doc”, it would be a lot better something like: “did you see this method in the java doc” ... the conversation started in a wrong way to my opinion, but I thank you again for your replies... – navy1978 Jun 17 '18 at 16:14

2 Answers2

6

If you want to set a duration :

ScheduledExecutorService exe = Executors.newSingleThreadScheduledExecutor();
// or Executors.newScheduledThreadPool(2); if you have multiple tasks
exe.schedule(() -> System.out.println("Executed at:" + (new Date())), 1, TimeUnit.MINUTES);

If you want to use a LocalDateTime :

ScheduledExecutorService exe = Executors.newSingleThreadScheduledExecutor();
// or Executors.newScheduledThreadPool(2); if you have multiple tasks
LocalDateTime date = LocalDateTime.of(2018, 6, 17, 18, 30, 0);
exe.schedule(
       () -> System.out.println("Executed at:" + (new Date())),
       LocalDateTime.now().until(date, ChronoUnit.MINUTES),
       TimeUnit.MINUTES);
azro
  • 53,056
  • 7
  • 34
  • 70
2

You can use ScheduledExecutorService.schedule(Runnable command, long delay, TimeUnit unit)

long delay = afterOneMinute.getTime() - System.currentTimeMillis();
ScheduledExecutorService executorService = ...;
executorService.schedule(runnable, delay, TimeUnit.MILLISECONDS);
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • I saw somebody gave you a down vote and I gave you an up one, because I think it's the correct way to do it, I could not find the schedule method in the JavaDoc that takes a Date as a parameters and I didn't see this without a period. I will accept your question, because it's what I need... Thank. you – navy1978 Jun 17 '18 at 16:01
  • 2
    I have the impression that some of the guys here love to give down votes... – navy1978 Jun 17 '18 at 16:02