0

Plan to run a job periodically and shut down the execution after certain duration to clean up the threads since the life time for the container is set to be 5 hours. Java ScheduledExecutorService provides the functionality to schedule the job periodically but the shutdown method will close the executor service immediately instead of after some duration. Is there a way to handle such case? Anyone knows if there is a better api to use in Java? Any suggestion is appreciated

dashenswen
  • 540
  • 2
  • 4
  • 21
  • Does this answer your question? [java ScheduleExecutorService timeout task](https://stackoverflow.com/questions/20279736/java-scheduleexecutorservice-timeout-task) – tkruse Mar 08 '20 at 01:55
  • Likely you will find an answer if you Google for "schedule with timeout". – tkruse Mar 08 '20 at 01:57
  • thanks. I was searching like "schedule executor service for certain duration" but with no luck..Don't know how I didn't search timeout! – dashenswen Mar 08 '20 at 02:48

1 Answers1

1

Why not schedule the Executor to shut itself down?

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(() -> System.out.println("tick"), 1, 1, TimeUnit.SECONDS);
    exec.scheduleAtFixedRate(exec::shutdown, 5, 1, TimeUnit.SECONDS);

It doesn't really matter whether the shutdown uses FixedRate or FixedDelay, since it will only run once.

jaco0646
  • 15,303
  • 7
  • 59
  • 83