callback_timer 0.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5443a3376ac4153cbebc4fe044abf8a16d7acfc135031e783e54666b65dbc074
4
+ data.tar.gz: 55b84d5abd524a13c75b2461d951d27ce887117e1464fae04100a3a0c42b15cc
5
+ SHA512:
6
+ metadata.gz: d8a65ef5c30e15450ba728e0222103bc3c137471cca00a4174a9b4064549ecdb3a13712f67a09a96101482274771416b9360349be42167110b44715aab1204a6
7
+ data.tar.gz: 310b3db17b748cccf29ded50cdbbb12299801829e53ee40e7993842b640bac4a5d3836df359ba5d8eb99cf32d3267de4c3cbad24f80d63d959c7d845dbf0b304
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 Rob Fors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,16 @@
1
+ # Callback Timer
2
+ A Ruby Gem to create timers. The timer objects will call a given callback when the time has elapsed or can be canceled before then. *Callback Timer* only uses a single thread to schedule all the timers.
3
+
4
+ # Install
5
+ `gem install callback_timer`
6
+
7
+ # Documentation
8
+ [![Yard Docs](https://img.shields.io/badge/yard-docs-blue.svg?style=for-the-badge)](http://www.rubydoc.info/gems/callback_timer)
9
+
10
+ # Example
11
+ ```ruby
12
+ require 'callback_timer'
13
+
14
+ greeting_callback = proc { puts 'Hello World!' }
15
+ CallbackTimer.new(callback: greeting_callback, duration: 5)
16
+ ```
@@ -0,0 +1,113 @@
1
+ require 'thread'
2
+ require 'time'
3
+
4
+ class CallbackTimer
5
+
6
+ # I would like to use a priority queue here but I need to be able to remove sleepers randomly.
7
+ #@timers = PQueue.new { |a, b| a < b }
8
+ @timers = []
9
+ @condition_variable = ConditionVariable.new
10
+ @mutex = Mutex.new
11
+ @thread = Thread.new { worker_loop }
12
+
13
+ # Add {CallbackTimer} to the scheduler.
14
+ # @api private
15
+ # @param timer [CallbackTimer]
16
+ # @return [void]
17
+ def self.add(timer)
18
+ @mutex.synchronize do
19
+ @timers.push(timer)
20
+ @timers.sort_by!(&:deadline)
21
+ if @timers.first == timer
22
+ @condition_variable.signal
23
+ end
24
+ end
25
+ nil
26
+ end
27
+
28
+ # Remove {CallbackTimer} from scheduler.
29
+ # @api private
30
+ # @param timer [CallbackTimer]
31
+ # @return [void]
32
+ def self.cancel(timer)
33
+ @mutex.synchronize do
34
+ @condition_variable.signal if @timers.first == timer
35
+ @timers.delete(timer)
36
+ end
37
+ nil
38
+ end
39
+
40
+ # Scheduler worker loop to run in it's own thread.
41
+ # @api private
42
+ # @return [void]
43
+ def self.worker_loop
44
+ @mutex.lock
45
+ loop do
46
+ next_timer = @timers.first
47
+ unless next_timer
48
+ @condition_variable.wait(@mutex)
49
+ next
50
+ end
51
+ next_deadline = next_timer.deadline
52
+ duration = next_deadline - Time.now
53
+ @condition_variable.wait(@mutex, duration) if duration.positive?
54
+ if @timers.first != next_timer
55
+ # timer may have been canceled or a new timer has been added to @timers with an earlier deadline
56
+ next
57
+ end
58
+ @timers.shift
59
+ @mutex.unlock
60
+ next_timer.time_has_elapsed
61
+ @mutex.lock
62
+ end
63
+ nil
64
+ end
65
+
66
+ # Time that the {CallbackTimer} should call it's callback.
67
+ # @api private
68
+ # @return [Time]
69
+ attr_reader :deadline
70
+
71
+ # Creates and starts a new {CallbackTimer}.
72
+ # @param callback [#to_proc]
73
+ # @param duration [Numeric] non-negative number specified in seconds
74
+ # @return [CallbackTimer]
75
+ def initialize(callback: , duration: )
76
+ raise ArgumentError, "'callback' must respond to 'to_proc'" unless callback.respond_to?(:to_proc)
77
+ @callback = callback.to_proc
78
+ unless duration.is_a?(Numeric) && duration >= 0
79
+ raise ArgumentError, "'duration' must be a non-negative Numeric"
80
+ end
81
+ @start_time = Time.now
82
+ @deadline = @start_time + duration
83
+ @mutex = Mutex.new
84
+ @complete = false
85
+ self.class.add(self)
86
+ end
87
+
88
+ # Cancels the {CallbackTimer}.
89
+ # Will ignore if already called or if callback has already been called.
90
+ # @return [void]
91
+ def cancel
92
+ @mutex.synchronize do
93
+ return if @complete
94
+ @complete = true
95
+ end
96
+ self.class.cancel(self)
97
+ nil
98
+ end
99
+
100
+ # Tells {CallbackTimer} it has reached it's deadline.
101
+ # @api private
102
+ # @return [void]
103
+ def time_has_elapsed
104
+ @mutex.synchronize do
105
+ return if @complete
106
+ @complete = true
107
+ end
108
+ elapsed_time = Time.now - @start_time
109
+ @callback.call(elapsed_time)
110
+ nil
111
+ end
112
+
113
+ end
@@ -0,0 +1,99 @@
1
+ require 'callback_timer'
2
+
3
+
4
+ require 'pry'
5
+
6
+ RSpec.describe CallbackTimer do
7
+
8
+ describe "::new" do
9
+
10
+ context "when creating a new CallbackTimer with no 'duration'" do
11
+ it "should raise ArgumentError" do
12
+ callback = proc {}
13
+ expect{ CallbackTimer.new(callback: callback) }.to raise_error(ArgumentError)
14
+ end
15
+ end
16
+
17
+ context "when creating a new CallbackTimer with a negative 'duration'" do
18
+ it "should raise ArgumentError" do
19
+ callback = proc {}
20
+ duration = -1
21
+ expect{ CallbackTimer.new(callback: callback, duration: duration) }.to raise_error(ArgumentError)
22
+ end
23
+ end
24
+
25
+ context "when creating a new CallbackTimer with no 'callback'" do
26
+ it "should raise ArgumentError" do
27
+ duration = 1
28
+ expect{ CallbackTimer.new(duration: duration) }.to raise_error(ArgumentError)
29
+ end
30
+ end
31
+
32
+ context "when creating a new CallbackTimer with a 'duration' of 1" do
33
+ it "should call the callback in 1 second" do
34
+ $test = nil
35
+ target_time = Time.now + 1
36
+ callback = proc { $test = Time.now }
37
+ CallbackTimer.new(callback: callback, duration: 1)
38
+ sleep 2
39
+ expect($test).to be_between(target_time - 0.2, target_time + 0.2)
40
+ end
41
+ end
42
+
43
+ context "when creating three new CallbackTimers with different 'duration's" do
44
+ it "should all call the callback at correct times" do
45
+ #binding.pry
46
+ $tt = 0
47
+ $test = []
48
+ start_time = Time.now
49
+ durations = [1, 0.5, 2]
50
+ target_times = durations.map { |duration| start_time + duration }
51
+ callbacks = 3.times.map { |index| proc { $test[index] = Time.now } }
52
+ 3.times { |index| CallbackTimer.new(callback: callbacks[index], duration: durations[index]) }
53
+ sleep 2.2
54
+ 3.times { |index| expect($test[index]).to be_between(target_times[index] - 0.2, target_times[index] + 0.2) }
55
+ end
56
+ end
57
+
58
+ context "when creating a lot of new CallbackTimers with different 'duration's" do
59
+ it "should all call the callback at correct times" do
60
+ $test = []
61
+ start_time = Time.now
62
+ random = Random.new(1234)
63
+ durations = 100.times.map { random.rand(0.0..10.0) }
64
+ target_times = durations.map { |duration| start_time + duration }
65
+ callbacks = 100.times.map { |index| proc { $test[index] = Time.now } }
66
+ 100.times { |index| CallbackTimer.new(callback: callbacks[index], duration: durations[index]) }
67
+ sleep 10.2
68
+ 100.times { |index| expect($test[index]).to be_between(target_times[index] - 0.2, target_times[index] + 0.2) }
69
+ end
70
+ end
71
+
72
+ end
73
+
74
+ describe "#cancel" do
75
+
76
+ context "when calling #cancel on a pending CallbackTimer" do
77
+ it "should not call callback" do
78
+ $called = false
79
+ callback = proc { $called = true }
80
+ timer = CallbackTimer.new(callback: callback, duration: 2)
81
+ sleep 1
82
+ timer.cancel
83
+ sleep 2
84
+ expect($called).to eql false
85
+ end
86
+ end
87
+
88
+ context "when calling #cancel on completed CallbackTimer" do
89
+ it "should do nothing" do
90
+ callback = proc { }
91
+ timer = CallbackTimer.new(callback: callback, duration: 1)
92
+ sleep 2
93
+ expect{ timer.cancel }.not_to raise_error
94
+ end
95
+ end
96
+
97
+ end
98
+
99
+ end
@@ -0,0 +1,100 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # The generated `.rspec` file contains `--require spec_helper` which will cause
4
+ # this file to always be loaded, without a need to explicitly require it in any
5
+ # files.
6
+ #
7
+ # Given that it is always loaded, you are encouraged to keep this file as
8
+ # light-weight as possible. Requiring heavyweight dependencies from this file
9
+ # will add to the boot time of your test suite on EVERY test run, even for an
10
+ # individual file that may not need all of that loaded. Instead, consider making
11
+ # a separate helper file that requires the additional dependencies and performs
12
+ # the additional setup, and require it from the spec files that actually need
13
+ # it.
14
+ #
15
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
16
+ RSpec.configure do |config|
17
+ # rspec-expectations config goes here. You can use an alternate
18
+ # assertion/expectation library such as wrong or the stdlib/minitest
19
+ # assertions if you prefer.
20
+ config.expect_with :rspec do |expectations|
21
+ # This option will default to `true` in RSpec 4. It makes the `description`
22
+ # and `failure_message` of custom matchers include text for helper methods
23
+ # defined using `chain`, e.g.:
24
+ # be_bigger_than(2).and_smaller_than(4).description
25
+ # # => "be bigger than 2 and smaller than 4"
26
+ # ...rather than:
27
+ # # => "be bigger than 2"
28
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
29
+ end
30
+
31
+ # rspec-mocks config goes here. You can use an alternate test double
32
+ # library (such as bogus or mocha) by changing the `mock_with` option here.
33
+ config.mock_with :rspec do |mocks|
34
+ # Prevents you from mocking or stubbing a method that does not exist on
35
+ # a real object. This is generally recommended, and will default to
36
+ # `true` in RSpec 4.
37
+ mocks.verify_partial_doubles = true
38
+ end
39
+
40
+ # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
41
+ # have no way to turn it off -- the option exists only for backwards
42
+ # compatibility in RSpec 3). It causes shared context metadata to be
43
+ # inherited by the metadata hash of host groups and examples, rather than
44
+ # triggering implicit auto-inclusion in groups with matching metadata.
45
+ config.shared_context_metadata_behavior = :apply_to_host_groups
46
+
47
+ # The settings below are suggested to provide a good initial experience
48
+ # with RSpec, but feel free to customize to your heart's content.
49
+ =begin
50
+ # This allows you to limit a spec run to individual examples or groups
51
+ # you care about by tagging them with `:focus` metadata. When nothing
52
+ # is tagged with `:focus`, all examples get run. RSpec also provides
53
+ # aliases for `it`, `describe`, and `context` that include `:focus`
54
+ # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
55
+ config.filter_run_when_matching :focus
56
+
57
+ # Allows RSpec to persist some state between runs in order to support
58
+ # the `--only-failures` and `--next-failure` CLI options. We recommend
59
+ # you configure your source control system to ignore this file.
60
+ config.example_status_persistence_file_path = "spec/examples.txt"
61
+
62
+ # Limits the available syntax to the non-monkey patched syntax that is
63
+ # recommended. For more details, see:
64
+ # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
65
+ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
66
+ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
67
+ config.disable_monkey_patching!
68
+
69
+ # This setting enables warnings. It's recommended, but in some cases may
70
+ # be too noisy due to issues in dependencies.
71
+ config.warnings = true
72
+
73
+ # Many RSpec users commonly either run the entire suite or an individual
74
+ # file, and it's useful to allow more verbose output when running an
75
+ # individual spec file.
76
+ if config.files_to_run.one?
77
+ # Use the documentation formatter for detailed output,
78
+ # unless a formatter has already been configured
79
+ # (e.g. via a command-line flag).
80
+ config.default_formatter = "doc"
81
+ end
82
+
83
+ # Print the 10 slowest examples and example groups at the
84
+ # end of the spec run, to help surface which specs are running
85
+ # particularly slow.
86
+ config.profile_examples = 10
87
+
88
+ # Run specs in random order to surface order dependencies. If you find an
89
+ # order dependency and want to debug it, you can fix the order by providing
90
+ # the seed, which is printed after each run.
91
+ # --seed 1234
92
+ config.order = :random
93
+
94
+ # Seed global randomization in this process using the `--seed` CLI option.
95
+ # Setting this allows you to use `--seed` to deterministically reproduce
96
+ # test failures related to randomization by passing the same `--seed` value
97
+ # as the one that triggered the failure.
98
+ Kernel.srand config.seed
99
+ =end
100
+ end
metadata ADDED
@@ -0,0 +1,49 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: callback_timer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Rob Fors
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-04-27 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Create cancelable timer objects that will call a given callback when
14
+ time has elapsed. Implemented using a single scheduling thread.
15
+ email: mail@robfors.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - lib/callback_timer.rb
23
+ - spec/callback_timer_spec.rb
24
+ - spec/spec_helper.rb
25
+ homepage: https://github.com/robfors/callback_timer
26
+ licenses:
27
+ - MIT
28
+ metadata: {}
29
+ post_install_message:
30
+ rdoc_options: []
31
+ require_paths:
32
+ - lib
33
+ required_ruby_version: !ruby/object:Gem::Requirement
34
+ requirements:
35
+ - - ">="
36
+ - !ruby/object:Gem::Version
37
+ version: 2.3.0
38
+ required_rubygems_version: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '0'
43
+ requirements: []
44
+ rubyforge_project:
45
+ rubygems_version: 2.7.6
46
+ signing_key:
47
+ specification_version: 4
48
+ summary: Create timers that support a callback.
49
+ test_files: []