dashenswen
dashenswen

Reputation: 600

How to run a job periodically and within certain duration

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

Upvotes: 0

Views: 71

Answers (1)

jaco0646
jaco0646

Reputation: 17066

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.

Upvotes: 1

Related Questions