File: scheduled_task.rb

package info (click to toggle)
ruby-concurrent 1.1.6%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 30,284 kB
  • sloc: ruby: 30,875; java: 6,117; javascript: 1,114; ansic: 288; makefile: 10; sh: 6
file content (318 lines) | stat: -rw-r--r-- 10,984 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
require 'concurrent/constants'
require 'concurrent/errors'
require 'concurrent/configuration'
require 'concurrent/ivar'
require 'concurrent/collection/copy_on_notify_observer_set'
require 'concurrent/utility/monotonic_time'

require 'concurrent/options'

module Concurrent

  # `ScheduledTask` is a close relative of `Concurrent::Future` but with one
  # important difference: A `Future` is set to execute as soon as possible
  # whereas a `ScheduledTask` is set to execute after a specified delay. This
  # implementation is loosely based on Java's
  # [ScheduledExecutorService](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html).
  # It is a more feature-rich variant of {Concurrent.timer}.
  #
  # The *intended* schedule time of task execution is set on object construction
  # with the `delay` argument. The delay is a numeric (floating point or integer)
  # representing a number of seconds in the future. Any other value or a numeric
  # equal to or less than zero will result in an exception. The *actual* schedule
  # time of task execution is set when the `execute` method is called.
  #
  # The constructor can also be given zero or more processing options. Currently
  # the only supported options are those recognized by the
  # [Dereferenceable](Dereferenceable) module.
  #
  # The final constructor argument is a block representing the task to be performed.
  # If no block is given an `ArgumentError` will be raised.
  #
  # **States**
  #
  # `ScheduledTask` mixes in the  [Obligation](Obligation) module thus giving it
  # "future" behavior. This includes the expected lifecycle states. `ScheduledTask`
  # has one additional state, however. While the task (block) is being executed the
  # state of the object will be `:processing`. This additional state is necessary
  # because it has implications for task cancellation.
  #
  # **Cancellation**
  #
  # A `:pending` task can be cancelled using the `#cancel` method. A task in any
  # other state, including `:processing`, cannot be cancelled. The `#cancel`
  # method returns a boolean indicating the success of the cancellation attempt.
  # A cancelled `ScheduledTask` cannot be restarted. It is immutable.
  #
  # **Obligation and Observation**
  #
  # The result of a `ScheduledTask` can be obtained either synchronously or
  # asynchronously. `ScheduledTask` mixes in both the [Obligation](Obligation)
  # module and the
  # [Observable](http://ruby-doc.org/stdlib-2.0/libdoc/observer/rdoc/Observable.html)
  # module from the Ruby standard library. With one exception `ScheduledTask`
  # behaves identically to [Future](Observable) with regard to these modules.
  #
  # @!macro copy_options
  #
  # @example Basic usage
  #
  #   require 'concurrent'
  #   require 'thread'   # for Queue
  #   require 'open-uri' # for open(uri)
  #
  #   class Ticker
  #     def get_year_end_closing(symbol, year)
  #       uri = "http://ichart.finance.yahoo.com/table.csv?s=#{symbol}&a=11&b=01&c=#{year}&d=11&e=31&f=#{year}&g=m"
  #       data = open(uri) {|f| f.collect{|line| line.strip } }
  #       data[1].split(',')[4].to_f
  #     end
  #   end
  #
  #   # Future
  #   price = Concurrent::Future.execute{ Ticker.new.get_year_end_closing('TWTR', 2013) }
  #   price.state #=> :pending
  #   sleep(1)    # do other stuff
  #   price.value #=> 63.65
  #   price.state #=> :fulfilled
  #
  #   # ScheduledTask
  #   task = Concurrent::ScheduledTask.execute(2){ Ticker.new.get_year_end_closing('INTC', 2013) }
  #   task.state #=> :pending
  #   sleep(3)   # do other stuff
  #   task.value #=> 25.96
  #
  # @example Successful task execution
  #
  #   task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }
  #   task.state         #=> :unscheduled
  #   task.execute
  #   task.state         #=> pending
  #
  #   # wait for it...
  #   sleep(3)
  #
  #   task.unscheduled? #=> false
  #   task.pending?     #=> false
  #   task.fulfilled?   #=> true
  #   task.rejected?    #=> false
  #   task.value        #=> 'What does the fox say?'
  #
  # @example One line creation and execution
  #
  #   task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }.execute
  #   task.state         #=> pending
  #
  #   task = Concurrent::ScheduledTask.execute(2){ 'What do you get when you multiply 6 by 9?' }
  #   task.state         #=> pending
  #
  # @example Failed task execution
  #
  #   task = Concurrent::ScheduledTask.execute(2){ raise StandardError.new('Call me maybe?') }
  #   task.pending?      #=> true
  #
  #   # wait for it...
  #   sleep(3)
  #
  #   task.unscheduled? #=> false
  #   task.pending?     #=> false
  #   task.fulfilled?   #=> false
  #   task.rejected?    #=> true
  #   task.value        #=> nil
  #   task.reason       #=> #<StandardError: Call me maybe?>
  #
  # @example Task execution with observation
  #
  #   observer = Class.new{
  #     def update(time, value, reason)
  #       puts "The task completed at #{time} with value '#{value}'"
  #     end
  #   }.new
  #
  #   task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }
  #   task.add_observer(observer)
  #   task.execute
  #   task.pending?      #=> true
  #
  #   # wait for it...
  #   sleep(3)
  #
  #   #>> The task completed at 2013-11-07 12:26:09 -0500 with value 'What does the fox say?'
  #
  # @!macro monotonic_clock_warning
  #
  # @see Concurrent.timer
  class ScheduledTask < IVar
    include Comparable

    # The executor on which to execute the task.
    # @!visibility private
    attr_reader :executor

    # Schedule a task for execution at a specified future time.
    #
    # @param [Float] delay the number of seconds to wait for before executing the task
    #
    # @yield the task to be performed
    #
    # @!macro executor_and_deref_options
    #
    # @option opts [object, Array] :args zero or more arguments to be passed the task
    #   block on execution
    #
    # @raise [ArgumentError] When no block is given
    # @raise [ArgumentError] When given a time that is in the past
    def initialize(delay, opts = {}, &task)
      raise ArgumentError.new('no block given') unless block_given?
      raise ArgumentError.new('seconds must be greater than zero') if delay.to_f < 0.0

      super(NULL, opts, &nil)

      synchronize do
        ns_set_state(:unscheduled)
        @parent = opts.fetch(:timer_set, Concurrent.global_timer_set)
        @args = get_arguments_from(opts)
        @delay = delay.to_f
        @task = task
        @time = nil
        @executor = Options.executor_from_options(opts) || Concurrent.global_io_executor
        self.observers = Collection::CopyOnNotifyObserverSet.new
      end
    end

    # The `delay` value given at instanciation.
    #
    # @return [Float] the initial delay.
    def initial_delay
      synchronize { @delay }
    end

    # The monotonic time at which the the task is scheduled to be executed.
    #
    # @return [Float] the schedule time or nil if `unscheduled`
    def schedule_time
      synchronize { @time }
    end

    # Comparator which orders by schedule time.
    #
    # @!visibility private
    def <=>(other)
      schedule_time <=> other.schedule_time
    end

    # Has the task been cancelled?
    #
    # @return [Boolean] true if the task is in the given state else false
    def cancelled?
      synchronize { ns_check_state?(:cancelled) }
    end

    # In the task execution in progress?
    #
    # @return [Boolean] true if the task is in the given state else false
    def processing?
      synchronize { ns_check_state?(:processing) }
    end

    # Cancel this task and prevent it from executing. A task can only be
    # cancelled if it is pending or unscheduled.
    #
    # @return [Boolean] true if successfully cancelled else false
    def cancel
      if compare_and_set_state(:cancelled, :pending, :unscheduled)
        complete(false, nil, CancelledOperationError.new)
        # To avoid deadlocks this call must occur outside of #synchronize
        # Changing the state above should prevent redundant calls
        @parent.send(:remove_task, self)
      else
        false
      end
    end

    # Reschedule the task using the original delay and the current time.
    # A task can only be reset while it is `:pending`.
    #
    # @return [Boolean] true if successfully rescheduled else false
    def reset
      synchronize{ ns_reschedule(@delay) }
    end

    # Reschedule the task using the given delay and the current time.
    # A task can only be reset while it is `:pending`.
    #
    # @param [Float] delay the number of seconds to wait for before executing the task
    #
    # @return [Boolean] true if successfully rescheduled else false
    #
    # @raise [ArgumentError] When given a time that is in the past
    def reschedule(delay)
      delay = delay.to_f
      raise ArgumentError.new('seconds must be greater than zero') if delay < 0.0
      synchronize{ ns_reschedule(delay) }
    end

    # Execute an `:unscheduled` `ScheduledTask`. Immediately sets the state to `:pending`
    # and starts counting down toward execution. Does nothing if the `ScheduledTask` is
    # in any state other than `:unscheduled`.
    #
    # @return [ScheduledTask] a reference to `self`
    def execute
      if compare_and_set_state(:pending, :unscheduled)
        synchronize{ ns_schedule(@delay) }
      end
      self
    end

    # Create a new `ScheduledTask` object with the given block, execute it, and return the
    # `:pending` object.
    #
    # @param [Float] delay the number of seconds to wait for before executing the task
    #
    # @!macro executor_and_deref_options
    #
    # @return [ScheduledTask] the newly created `ScheduledTask` in the `:pending` state
    #
    # @raise [ArgumentError] if no block is given
    def self.execute(delay, opts = {}, &task)
      new(delay, opts, &task).execute
    end

    # Execute the task.
    #
    # @!visibility private
    def process_task
      safe_execute(@task, @args)
    end

    protected :set, :try_set, :fail, :complete

    protected

    # Schedule the task using the given delay and the current time.
    #
    # @param [Float] delay the number of seconds to wait for before executing the task
    #
    # @return [Boolean] true if successfully rescheduled else false
    #
    # @!visibility private
    def ns_schedule(delay)
      @delay = delay
      @time = Concurrent.monotonic_time + @delay
      @parent.send(:post_task, self)
    end

    # Reschedule the task using the given delay and the current time.
    # A task can only be reset while it is `:pending`.
    #
    # @param [Float] delay the number of seconds to wait for before executing the task
    #
    # @return [Boolean] true if successfully rescheduled else false
    #
    # @!visibility private
    def ns_reschedule(delay)
      return false unless ns_check_state?(:pending)
      @parent.send(:remove_task, self) && ns_schedule(delay)
    end
  end
end