java.util.concurrent
Class ScheduledExecutor
java.lang.Object
java.util.concurrent.ThreadPoolExecutor
java.util.concurrent.ScheduledExecutor
- All Implemented Interfaces:
- Executor, ExecutorService
- public class ScheduledExecutor
- extends ThreadPoolExecutor
An Executor
that can schedule commands to run after a given
delay, or to execute periodically. This class is preferable to
Timer
when multiple worker threads are needed,
or when the additional flexibility or capabilities of
ThreadPoolExecutor
(which this class extends) are
required.
The schedule methods create tasks with various delays
and return a task object that can be used to cancel or check
execution. The scheduleAtFixedRate and
scheduleWithFixedDelay methods create and execute tasks
that run periodically until cancelled. Commands submitted using
the execute method are scheduled with a requested delay of
zero.
Delayed tasks execute no sooner than they are enabled, but
without any real-time guarantees about when, after they are enabled,
they will commence. Tasks tied for the same execution time are
enabled in first-in-first-out (FIFO) order of submission.
All schedule methods accept relative delays and
periods as arguments, not absolute times or dates. It is a simple
matter to transform an absolute time represented as a Date
to the required form. For example, to schedule at
a certain future date, you can use: schedule(task,
date.getTime() - System.currentTimeMillis(),
TimeUnit.MILLISECONDS). Beware however that expiration of a
relative delay need not coincide with the current Date at
which the task is enabled due to network time synchronization
protocols, clock drift, or other factors. Negative relative delays
(but not periods) are allowed in schedule methods, and are
treated as requests for immediate execution.
While this class inherits from ThreadPoolExecutor
, a few
of the inherited tuning methods are not especially useful for
it. In particular, because a ScheduledExecutor always acts
as a fixed-sized pool using corePoolSize threads and an
unbounded queue, adjustments to maximumPoolSize have no
useful effect.
- Since:
- 1.5
Method Summary |
protected void |
afterExecute(Runnable r,
Throwable t)
Override of Executor hook method to support periodic
tasks. |
void |
execute(Runnable command)
Execute command with zero required delay. |
boolean |
getContinueExistingPeriodicTasksAfterShutdownPolicy()
Get the policy on whether to continue executing existing
periodic tasks even when this executor has been
shutdown. |
boolean |
getExecuteExistingDelayedTasksAfterShutdownPolicy()
Get policy on whether to execute existing delayed
tasks even when this executor has been shutdown. |
BlockingQueue<Runnable> |
getQueue()
Returns the task queue used by this executor. |
boolean |
remove(Runnable task)
Removes this task from internal queue if it is present, thus
causing it not to be run if it has not already started. |
|
schedule(Callable<V> callable,
long delay,
TimeUnit unit)
Creates and executes a ScheduledFuture that becomes enabled after the
given delay. |
ScheduledCancellable |
schedule(Runnable command,
long delay,
TimeUnit unit)
Creates and executes a one-shot action that becomes enabled after
the given delay. |
ScheduledCancellable |
scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit)
Creates and executes a periodic action that becomes enabled first
after the given initial delay, and subsequently with the given
period; that is executions will commence after
initialDelay then initialDelay+period, then
initialDelay + 2 * period, and so on. |
ScheduledCancellable |
scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit)
Creates and executes a periodic action that becomes enabled first
after the given initial delay, and subsequently with the
given delay between the termination of one execution and the
commencement of the next. |
void |
setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value)
Set policy on whether to continue executing existing periodic
tasks even when this executor has been shutdown. |
void |
setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value)
Set policy on whether to execute existing delayed
tasks even when this executor has been shutdown. |
void |
shutdown()
Initiates an orderly shutdown in which previously submitted
tasks are executed, but no new tasks will be accepted. |
List |
shutdownNow()
Attempts to stop all actively executing tasks, halts the
processing of waiting tasks, and returns a list of the tasks that were
awaiting execution. |
Methods inherited from class java.util.concurrent.ThreadPoolExecutor |
awaitTermination, beforeExecute, finalize, getActiveCount, getCompletedTaskCount, getCorePoolSize, getKeepAliveTime, getLargestPoolSize, getMaximumPoolSize, getPoolSize, getRejectedExecutionHandler, getTaskCount, getThreadFactory, isShutdown, isTerminated, isTerminating, prestartAllCoreThreads, prestartCoreThread, purge, setCorePoolSize, setKeepAliveTime, setMaximumPoolSize, setRejectedExecutionHandler, setThreadFactory, terminated |
ScheduledExecutor
public ScheduledExecutor(int corePoolSize)
- Creates a new ScheduledExecutor with the given core pool size.
- Parameters:
corePoolSize
- the number of threads to keep in the pool,
even if they are idle.
- Throws:
IllegalArgumentException
- if corePoolSize less than or
equal to zero
ScheduledExecutor
public ScheduledExecutor(int corePoolSize,
ThreadFactory threadFactory)
- Creates a new ScheduledExecutor with the given initial parameters.
- Parameters:
corePoolSize
- the number of threads to keep in the pool,
even if they are idle.threadFactory
- the factory to use when the executor
creates a new thread.
- Throws:
NullPointerException
- if threadFactory is null
ScheduledExecutor
public ScheduledExecutor(int corePoolSize,
RejectedExecutionHandler handler)
- Creates a new ScheduledExecutor with the given initial parameters.
- Parameters:
corePoolSize
- the number of threads to keep in the pool,
even if they are idle.handler
- the handler to use when execution is blocked
because the thread bounds and queue capacities are reached.
- Throws:
NullPointerException
- if handler is null
ScheduledExecutor
public ScheduledExecutor(int corePoolSize,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- Creates a new ScheduledExecutor with the given initial parameters.
- Parameters:
corePoolSize
- the number of threads to keep in the pool,
even if they are idle.threadFactory
- the factory to use when the executor
creates a new thread.handler
- the handler to use when execution is blocked
because the thread bounds and queue capacities are reached.
- Throws:
NullPointerException
- if threadFactory or handler is null
schedule
public ScheduledCancellable schedule(Runnable command,
long delay,
TimeUnit unit)
- Creates and executes a one-shot action that becomes enabled after
the given delay.
- Parameters:
command
- the task to execute.delay
- the time from now to delay execution.unit
- the time unit of the delay parameter.
- Returns:
- a handle that can be used to cancel the task.
- Throws:
RejectedExecutionException
- if task cannot be scheduled
for execution because the executor has been shut down.
NullPointerException
- if command is null
schedule
public <V> ScheduledFuture<V> schedule(Callable<V> callable,
long delay,
TimeUnit unit)
- Creates and executes a ScheduledFuture that becomes enabled after the
given delay.
- Parameters:
callable
- the function to execute.delay
- the time from now to delay execution.unit
- the time unit of the delay parameter.
- Returns:
- a ScheduledFuture that can be used to extract result or cancel.
- Throws:
RejectedExecutionException
- if task cannot be scheduled
for execution because the executor has been shut down.
NullPointerException
- if callable is null
scheduleAtFixedRate
public ScheduledCancellable scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit)
- Creates and executes a periodic action that becomes enabled first
after the given initial delay, and subsequently with the given
period; that is executions will commence after
initialDelay then initialDelay+period, then
initialDelay + 2 * period, and so on. The
task will only terminate via cancellation.
- Parameters:
command
- the task to execute.initialDelay
- the time to delay first execution.period
- the period between successive executions.unit
- the time unit of the delay and period parameters
- Returns:
- a handle that can be used to cancel the task.
- Throws:
RejectedExecutionException
- if task cannot be scheduled
for execution because the executor has been shut down.
NullPointerException
- if command is null
IllegalArgumentException
- if period less than or equal to zero.
scheduleWithFixedDelay
public ScheduledCancellable scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit)
- Creates and executes a periodic action that becomes enabled first
after the given initial delay, and subsequently with the
given delay between the termination of one execution and the
commencement of the next.
The task will only terminate via cancellation.
- Parameters:
command
- the task to execute.initialDelay
- the time to delay first execution.delay
- the delay between the termination of one
execution and the commencement of the next.unit
- the time unit of the delay and delay parameters
- Returns:
- a handle that can be used to cancel the task.
- Throws:
RejectedExecutionException
- if task cannot be scheduled
for execution because the executor has been shut down.
NullPointerException
- if command is null
IllegalArgumentException
- if delay less than or equal to zero.
execute
public void execute(Runnable command)
- Execute command with zero required delay. This has effect
equivalent to schedule(command, 0, anyUnit). Note
that inspections of the queue and of the list returned by
shutdownNow will access the zero-delayed
ScheduledCancellable
, not the command itself.
- Specified by:
execute
in interface Executor
- Overrides:
execute
in class ThreadPoolExecutor
- Parameters:
command
- the task to execute
- Throws:
RejectedExecutionException
- at discretion of
RejectedExecutionHandler, if task cannot be accepted
for execution because the executor has been shut down.
NullPointerException
- if command is null
setContinueExistingPeriodicTasksAfterShutdownPolicy
public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value)
- Set policy on whether to continue executing existing periodic
tasks even when this executor has been shutdown. In
this case, these tasks will only terminate upon
shutdownNow, or after setting the policy to
false when already shutdown. This value is by default
false.
- Parameters:
value
- if true, continue after shutdown, else don't.
getContinueExistingPeriodicTasksAfterShutdownPolicy
public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy()
- Get the policy on whether to continue executing existing
periodic tasks even when this executor has been
shutdown. In this case, these tasks will only
terminate upon shutdownNow or after setting the policy
to false when already shutdown. This value is by
default false.
- Returns:
- true if will continue after shutdown.
setExecuteExistingDelayedTasksAfterShutdownPolicy
public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value)
- Set policy on whether to execute existing delayed
tasks even when this executor has been shutdown. In
this case, these tasks will only terminate upon
shutdownNow, or after setting the policy to
false when already shutdown. This value is by default
true.
- Parameters:
value
- if true, execute after shutdown, else don't.
getExecuteExistingDelayedTasksAfterShutdownPolicy
public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy()
- Get policy on whether to execute existing delayed
tasks even when this executor has been shutdown. In
this case, these tasks will only terminate upon
shutdownNow, or after setting the policy to
false when already shutdown. This value is by default
true.
- Returns:
- true if will execute after shutdown.
shutdown
public void shutdown()
- Initiates an orderly shutdown in which previously submitted
tasks are executed, but no new tasks will be accepted. If the
ExecuteExistingDelayedTasksAfterShutdownPolicy has
been set false, existing delayed tasks whose delays
have not yet elapsed are cancelled. And unless the
ContinueExistingPeriodicTasksAfterShutdownPolicy has
been set true, future executions of existing periodic
tasks will be cancelled.
- Specified by:
shutdown
in interface ExecutorService
- Overrides:
shutdown
in class ThreadPoolExecutor
shutdownNow
public List shutdownNow()
- Attempts to stop all actively executing tasks, halts the
processing of waiting tasks, and returns a list of the tasks that were
awaiting execution.
There are no guarantees beyond best-effort attempts to stop
processing actively executing tasks. This implementations
cancels via Thread.interrupt()
, so if any tasks mask or
fail to respond to interrupts, they may never terminate.
- Specified by:
shutdownNow
in interface ExecutorService
- Overrides:
shutdownNow
in class ThreadPoolExecutor
- Returns:
- list of tasks that never commenced execution. Each
element of this list is a
ScheduledCancellable
,
including those tasks submitted using execute which
are for scheduling purposes used as the basis of a zero-delay
ScheduledCancellable.
remove
public boolean remove(Runnable task)
- Removes this task from internal queue if it is present, thus
causing it not to be run if it has not already started. This
method may be useful as one part of a cancellation scheme.
- Overrides:
remove
in class ThreadPoolExecutor
- Parameters:
task
- the task to remove
- Returns:
- true if the task was removed
getQueue
public BlockingQueue<Runnable> getQueue()
- Returns the task queue used by this executor. Each element of
this queue is a
ScheduledCancellable
, including those
tasks submitted using execute which are for scheduling
purposes used as the basis of a zero-delay
ScheduledCancellable. Iteration over this queue is
not guaranteed to traverse tasks in the order in
which they will execute.
- Overrides:
getQueue
in class ThreadPoolExecutor
- Returns:
- the task queue
afterExecute
protected void afterExecute(Runnable r,
Throwable t)
- Override of Executor hook method to support periodic
tasks. If the executed task was periodic, causes the task for
the next period to execute.
- Overrides:
afterExecute
in class ThreadPoolExecutor
- Parameters:
r
- the task (assumed to be a ScheduledCancellable)t
- the exception