문제

I am using ScheduledExecutorService, and after I call it's shutdown method, I can't schedule a Runnable on it. Calling scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS) after shutdown() throws java.util.concurrent.RejectedExecutionException. Is there another way to run a new task after shutdown() is called on ScheduledExecutorService?

도움이 되었습니까?

해결책

You can reuse the scheduler, but you shouldn't shutdown it. Rather, cancel the running thread which you can get when invoking scheduleAtFixedRate method. Ex:

//get reference to the future
Future<?> future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
//cancel instead of shutdown
future.cancel(true);
//schedule again (reuse)
future = service.scheduleAtFixedRate(runnable, INITIAL_DELAY, INTERVAL, TimeUnit.SECONDS)
//shutdown when you don't need to reuse the service anymore
service.shutdown()

다른 팁

The javadocs of shutdown() say:

Initiates an orderly shutdown in which previously submitted tasks are executed,
but no new tasks will be accepted.

So, you cannot call shutdow() and then schedule new tasks.

You can't make your executor accept new tasks after shutting it down. The more relevant question is why you need to shut it down in the first place? The executors you create should be re-used across the lifetime of your application or sub-system.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top