Class: Concurrent::TimerTask
Relationships & Source Files | |
Super Chains via Extension / Inclusion / Inheritance | |
Class Chain:
|
|
Instance Chain:
|
|
Inherits: | Concurrent::RubyExecutorService |
Defined in: | lib/concurrent-ruby/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.
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.
A TimerTask
supports two different types of interval calculations. A fixed delay will always wait the same amount of time between the completion of one task and the start of the next. A fixed rate will attempt to maintain a constant rate of execution regardless of the duration of the task. For example, if a fixed rate task is scheduled to run every 60 seconds but the task itself takes 10 seconds to complete, the next task will be scheduled to run 50 seconds after the start of the previous task. If the task takes 70 seconds to complete, the next task will be start immediately after the previous task completes. Tasks will not be executed concurrently.
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).
## Copy Options
::Object
references in Ruby are mutable. This can lead to serious problems when the #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_deref
When true the object will call the#dup
method on thevalue
object every time the#value
method is called (default: false) -
:freeze_on_deref
When true the object will call the#freeze
method on thevalue
object every time the#value
method is called (default: false) -
:copy_on_deref
When given aProc
object theProc
will be run every time the#value
method is called. TheProc
will be given the currentvalue
as its only argument and the result returned by the block will be the return value of the#value
call. Whennil
this 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
-
DEFAULT_INTERVAL_TYPE =
Default
:interval_type
FIXED_DELAY
-
EXECUTION_INTERVAL =
Default
:execution_interval
in seconds.60
-
FIXED_DELAY =
Maintain the interval between the end of one execution and the start of the next execution.
:fixed_delay
-
FIXED_RATE =
Maintain the interval between the start of one execution and the start of the next. If execution time exceeds the interval, the next execution will start immediately after the previous execution finishes. Executions will not run concurrently.
:fixed_rate
Concern::Logging
- Included
AbstractExecutorService
- Inherited
Class Method Summary
-
.execute(opts = {}) {|task| ... } ⇒ TimerTask
Create and execute a new
TimerTask
. -
.new(opts = {}, &task) ⇒ TimerTask
constructor
Create a new
TimerTask
with the given task and configuration.
RubyExecutorService
- Inherited
AbstractExecutorService
- Inherited
.new | Create a new thread pool. |
Instance Attribute Summary
- #execution_interval ⇒ Fixnum rw
-
#execution_interval=(value)
rw
See additional method definition at line 259.
- #interval_type ⇒ Symbol readonly
-
#running? ⇒ Boolean
readonly
Is the executor running?
- #timeout_interval ⇒ Fixnum rw
-
#timeout_interval=(value)
rw
See additional method definition at line 281.
Concern::Dereferenceable
- Included
#value | Return the value this object represents after applying the options specified by the |
RubyExecutorService
- Inherited
AbstractExecutorService
- Inherited
#auto_terminate= |
|
#auto_terminate? | Is the executor auto-terminate when the application exits? |
#fallback_policy, #name, | |
#running? | Is the executor running? |
#shutdown | Begin an orderly shutdown. |
#shutdown? | Is the executor shutdown? |
#shuttingdown? | Is the executor shuttingdown? |
#ns_auto_terminate? |
ExecutorService
- Included
#can_overflow? | Does the task queue have a maximum size? |
#serialized? | Does this executor guarantee serialization of its operations? |
Instance Method Summary
-
#execute ⇒ TimerTask
Execute a previously created
TimerTask
. - #calculate_next_interval(start_time) private
- #execute_task(completion) private
- #ns_initialize(opts, &task) private
- #ns_kill_execution private
- #ns_shutdown_execution private
- #schedule_next_task(interval = execution_interval) private
Concern::Observable
- Included
#add_observer | Adds an observer to this set. |
#count_observers | Return the number of observers associated with this object. |
#delete_observer | Remove |
#delete_observers | Remove all observers associated with this object. |
#with_observer | As |
Concern::Dereferenceable
- Included
#deref | Alias for Concern::Dereferenceable#value. |
#apply_deref_options, | |
#ns_set_deref_options |
|
RubyExecutorService
- Inherited
#<< | Submit a task to the executor for asynchronous processing. |
#auto_terminate= |
|
#auto_terminate? | Is the executor auto-terminate when the application exits? |
#can_overflow? | Does the task queue have a maximum size? |
#kill | Begin an immediate shutdown. |
#post | Submit a task to the executor for asynchronous processing. |
#running? | Is the executor running? |
#serialized? | Does this executor guarantee serialization of its operations? |
#shutdown | Begin an orderly shutdown. |
#shutdown? | Is the executor shutdown? |
#shuttingdown? | Is the executor shuttingdown? |
#wait_for_termination | Block until executor shutdown is complete or until |
#ns_shutdown_execution, #stop_event, #stopped_event |
AbstractExecutorService
- Inherited
#<< | Submit a task to the executor for asynchronous processing. |
#can_overflow? | Does the task queue have a maximum size? |
#kill | Begin an immediate shutdown. |
#post | Submit a task to the executor for asynchronous processing. |
#serialized? | Does this executor guarantee serialization of its operations? |
#to_s, | |
#wait_for_termination | Block until executor shutdown is complete or until |
#fallback_action | Returns an action which executes the |
#ns_execute, | |
#ns_kill_execution | Callback method called when the executor has been killed. |
#ns_shutdown_execution | Callback method called when an orderly shutdown has completed. |
Concern::Deprecation
- Included
ExecutorService
- Included
#<< | Submit a task to the executor for asynchronous processing. |
#post | Submit a task to the executor for asynchronous processing. |
Concern::Logging
- Included
#log | Logs through global_logger, it can be overridden by setting @logger. |
Synchronization::LockableObject
- Inherited
Constructor Details
.new(opts = {}, &task) ⇒ TimerTask
Create a new TimerTask
with the given task and configuration.
# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 209
def initialize(opts = {}, &task) raise ArgumentError.new('no block given') unless block_given? super opts end
Class Method Details
.execute(opts = {}) {|task| ... } ⇒ TimerTask
Create and execute a new TimerTask
.
# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 252
def self.execute(opts = {}, &task) TimerTask.new(opts, &task).execute end
Instance Attribute Details
#execution_interval ⇒ Fixnum
(rw)
# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 259
def execution_interval synchronize { @execution_interval } end
#execution_interval=(value) (rw)
See additional method definition at line 259.
# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 266
def execution_interval synchronize { @execution_interval } end
#interval_type ⇒ Symbol
(readonly)
# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 276
attr_reader :interval_type
#running? ⇒ Boolean
(readonly)
Is the executor running?
# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 218
def running? @running.true? end
#timeout_interval ⇒ Fixnum
(rw)
# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 281
def timeout_interval warn 'TimerTask timeouts are now ignored as these were not able to be implemented correctly' end
#timeout_interval=(value) (rw)
See additional method definition at line 281.
# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 288
def timeout_interval warn 'TimerTask timeouts are now ignored as these were not able to be implemented correctly' end
Instance Method Details
#calculate_next_interval(start_time) (private)
[ GitHub ]# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 352
def calculate_next_interval(start_time) if @interval_type == FIXED_RATE run_time = Concurrent.monotonic_time - start_time [execution_interval - run_time, 0].max else # FIXED_DELAY execution_interval end end
#execute ⇒ TimerTask
Execute a previously created TimerTask
.
# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 235
def execute synchronize do if @running.false? @running.make_true schedule_next_task(@run_now ? 0 : @execution_interval) end end self end
#execute_task(completion) (private)
[ GitHub ]# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 336
def execute_task(completion) return nil unless @running.true? start_time = Concurrent.monotonic_time _success, value, reason = @task.execute(self) if completion.try? self.value = value schedule_next_task(calculate_next_interval(start_time)) time = Time.now observers.notify_observers do [time, self.value, reason] end end nil end
#ns_initialize(opts, &task) (private)
[ GitHub ]# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 296
def ns_initialize(opts, &task) (opts) self.execution_interval = opts[:execution] || opts[:execution_interval] || EXECUTION_INTERVAL if opts[:interval_type] && ![FIXED_DELAY, FIXED_RATE].include?(opts[:interval_type]) raise ArgumentError.new('interval_type must be either :fixed_delay or :fixed_rate') end if opts[:timeout] || opts[:timeout_interval] warn 'TimeTask timeouts are now ignored as these were not able to be implemented correctly' end @run_now = opts[:now] || opts[:run_now] @interval_type = opts[:interval_type] || DEFAULT_INTERVAL_TYPE @task = Concurrent::SafeTaskExecutor.new(task) @executor = opts[:executor] || Concurrent.global_io_executor @running = Concurrent::AtomicBoolean.new(false) @value = nil self.observers = Collection::CopyOnNotifyObserverSet.new end
#ns_kill_execution (private)
[ GitHub ]# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 324
def ns_kill_execution @running.make_false super end
#ns_shutdown_execution (private)
[ GitHub ]# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 318
def ns_shutdown_execution @running.make_false super end
#schedule_next_task(interval = execution_interval) (private)
[ GitHub ]# File 'lib/concurrent-ruby/concurrent/timer_task.rb', line 330
def schedule_next_task(interval = execution_interval) ScheduledTask.execute(interval, executor: @executor, args: [Concurrent::Event.new], &method(:execute_task)) nil end