Class: Concurrent::TimerTask
- Inherits:
-
RubyExecutorService
- Object
- Synchronization::LockableObject
- AbstractExecutorService
- RubyExecutorService
- Concurrent::TimerTask
- Includes:
- Concern::Dereferenceable, Concern::Observable
- Defined in:
- lib/concurrent/timer_task.rb
Overview
A very common concurrency pattern is to run a thread that performs a task at
regular intervals. The thread that performs the task sleeps for the given
interval then wakes up and performs the task. Lather, rinse, repeat... This
pattern causes two problems. First, it is difficult to test the business
logic of the task because the task itself is tightly coupled with the
concurrency logic. Second, an exception raised while performing the task can
cause the entire thread to abend. In a long-running application where the
task thread is intended to run for days/weeks/years a crashed task thread
can pose a significant problem. TimerTask alleviates both problems.
When a TimerTask is launched it starts a thread for monitoring the
execution interval. The TimerTask thread does not perform the task,
however. Instead, the TimerTask launches the task on a separate thread.
Should the task experience an unrecoverable crash only the task thread will
crash. This makes the TimerTask very fault tolerant. Additionally, the
TimerTask thread can respond to the success or failure of the task,
performing logging or ancillary operations. TimerTask can also be
configured with a timeout value allowing it to kill a task that runs too
long.
One other advantage of TimerTask is that it forces the business logic to
be completely decoupled from the concurrency logic. The business logic can
be tested separately then passed to the TimerTask for scheduling and
running.
In some cases it may be necessary for a TimerTask to affect its own
execution cycle. To facilitate this, a reference to the TimerTask instance
is passed as an argument to the provided block every time the task is
executed.
The TimerTask class includes the Dereferenceable mixin module so the
result of the last execution is always available via the #value method.
Dereferencing options can be passed to the TimerTask during construction or
at any later time using the #set_deref_options method.
TimerTask supports notification through the Ruby standard library
Observable module. On execution the TimerTask will notify the observers
with three arguments: time of execution, the result of the block (or nil on
failure), and any raised exceptions (or nil on success). If the timeout
interval is exceeded the observer will receive a Concurrent::TimeoutError
object as the third argument.
Copy Options
Object references in Ruby are mutable. This can lead to serious
problems when the Concern::Dereferenceable#value of an object is a mutable reference. Which
is always the case unless the value is a Fixnum, Symbol, or similar
"primitive" data type. Each instance can be configured with a few
options that can help protect the program from potentially dangerous
operations. Each of these options can be optionally set when the object
instance is created:
:dup_on_derefWhen true the object will call the#dupmethod on thevalueobject every time the#valuemethod is called (default: false):freeze_on_derefWhen true the object will call the#freezemethod on thevalueobject every time the#valuemethod is called (default: false):copy_on_derefWhen given aProcobject theProcwill be run every time the#valuemethod is called. TheProcwill be given the currentvalueas its only argument and the result returned by the block will be the return value of the#valuecall. Whennilthis option will be ignored (default: nil)
When multiple deref options are set the order of operations is strictly defined. The order of deref operations is:
:copy_on_deref:dup_on_deref:freeze_on_deref
Because of this ordering there is no need to #freeze an object created by a
provided :copy_on_deref block. Simply set :freeze_on_deref to true.
Setting both :dup_on_deref to true and :freeze_on_deref to true is
as close to the behavior of a "pure" functional language (like Erlang, Clojure,
or Haskell) as we are likely to get in Ruby.
Constant Summary
- EXECUTION_INTERVAL =
Default
:execution_intervalin seconds. 60- TIMEOUT_INTERVAL =
Default
:timeout_intervalin seconds. 30
Instance Attribute Summary (collapse)
-
- (Fixnum) execution_interval
Number of seconds after the task completes before the task is performed again.
-
- (Symbol) fallback_policy
inherited
from RubyExecutorService
readonly
The fallback policy in effect.
-
- (Symbol) fallback_policy
inherited
from AbstractExecutorService
readonly
The fallback policy in effect.
-
- (Fixnum) timeout_interval
Number of seconds the task can run before it is considered to have failed.
Class Method Summary (collapse)
-
+ (TimerTask) execute(opts = {}) {|task| ... }
Create and execute a new
TimerTask.
Instance Method Summary (collapse)
-
- (Object) add_observer(observer = nil, func = :update, &block)
included
from Concern::Observable
Adds an observer to this set.
-
- (Integer) count_observers
included
from Concern::Observable
Return the number of observers associated with this object.
-
- (Object) delete_observer(observer)
included
from Concern::Observable
Remove
observeras an observer on this object so that it will no longer receive notifications. -
- (Observable) delete_observers
included
from Concern::Observable
Remove all observers associated with this object.
-
- (TimerTask) execute
Execute a previously created
TimerTask. -
- (TimerTask) initialize(opts = {}) {|task| ... }
constructor
Create a new TimerTask with the given task and configuration.
-
- (Boolean) running?
Is the executor running?.
-
- (Object) value
(also: #deref)
included
from Concern::Dereferenceable
Return the value this object represents after applying the options specified by the
#set_deref_optionsmethod. -
- (Observable) with_observer(observer = nil, func = :update, &block)
included
from Concern::Observable
As
#add_observerbut can be used for chaining.
Constructor Details
- (TimerTask) initialize(opts = {}) {|task| ... }
Create a new TimerTask with the given task and configuration.
189 190 191 192 |
# File 'lib/concurrent/timer_task.rb', line 189 def initialize(opts = {}, &task) raise ArgumentError.new('no block given') unless block_given? super end |
Instance Attribute Details
- (Fixnum) execution_interval
Returns Number of seconds after the task completes before the task is performed again.
238 239 240 |
# File 'lib/concurrent/timer_task.rb', line 238 def execution_interval synchronize { @execution_interval } end |
- (Symbol) fallback_policy (readonly) Originally defined in class RubyExecutorService
Returns The fallback policy in effect. Either :abort, :discard, or :caller_runs.
- (Symbol) fallback_policy (readonly) Originally defined in class AbstractExecutorService
Returns The fallback policy in effect. Either :abort, :discard, or :caller_runs.
- (Fixnum) timeout_interval
Returns Number of seconds the task can run before it is considered to have failed.
256 257 258 |
# File 'lib/concurrent/timer_task.rb', line 256 def timeout_interval synchronize { @timeout_interval } end |
Class Method Details
+ (TimerTask) execute(opts = {}) {|task| ... }
Create and execute a new TimerTask.
231 232 233 |
# File 'lib/concurrent/timer_task.rb', line 231 def self.execute(opts = {}, &task) TimerTask.new(opts, &task).execute end |
Instance Method Details
- (Object) add_observer(observer = nil, func = :update, &block) Originally defined in module Concern::Observable
Adds an observer to this set. If a block is passed, the observer will be created by this method and no other params should be passed.
- (Integer) count_observers Originally defined in module Concern::Observable
Return the number of observers associated with this object.
- (Object) delete_observer(observer) Originally defined in module Concern::Observable
Remove observer as an observer on this object so that it will no
longer receive notifications.
- (Observable) delete_observers Originally defined in module Concern::Observable
Remove all observers associated with this object.
- (TimerTask) execute
Execute a previously created TimerTask.
214 215 216 217 218 219 220 221 222 |
# File 'lib/concurrent/timer_task.rb', line 214 def execute synchronize do if @running.false? @running.make_true schedule_next_task(@run_now ? 0 : @execution_interval) end end self end |
- (Boolean) running?
Is the executor running?
197 198 199 |
# File 'lib/concurrent/timer_task.rb', line 197 def running? @running.true? end |
- (Object) value Also known as: deref Originally defined in module Concern::Dereferenceable
Return the value this object represents after applying the options specified
by the #set_deref_options method.
- (Observable) with_observer(observer = nil, func = :update, &block) Originally defined in module Concern::Observable
As #add_observer but can be used for chaining.