event_loop 0.1.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
+ SHA1:
3
+ metadata.gz: 5fa1c103a32ab4a1576b63e90b8d3906f86bb1fc
4
+ data.tar.gz: 0c8fc180a51e70c738ade71841220b3520ab4d1e
5
+ SHA512:
6
+ metadata.gz: f46f4f21f56e7f2de86781c9b05a0fdbbea37762a68d005dac4901c1dd98ff6385caf7fc5b8ebbfde06a17be1341a853434316abdc23918210d21f566f7d83f2
7
+ data.tar.gz: b379a79f704e03730476cfd670c90f27d0bf5994b6861c7ee602190f5fcada01e054428ea95fd8b9227de33bb884b93c317153b1289840880b2192fd5e74e202
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.idea/.rakeTasks ADDED
@@ -0,0 +1,7 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <Settings><!--This file was automatically generated by Ruby plugin.
3
+ You are allowed to:
4
+ 1. Remove rake task
5
+ 2. Add existing rake tasks
6
+ To add existing rake tasks automatically delete this file and reload the project.
7
+ --><RakeGroup description="" fullCmd="" taksId="rake"><RakeTask description="Build event_loop-0.1.0.gem into the pkg directory" fullCmd="build" taksId="build" /><RakeTask description="Remove any temporary products" fullCmd="clean" taksId="clean" /><RakeTask description="Remove any generated files" fullCmd="clobber" taksId="clobber" /><RakeTask description="Build and install event_loop-0.1.0.gem into system gems" fullCmd="install" taksId="install" /><RakeGroup description="" fullCmd="" taksId="install"><RakeTask description="Build and install event_loop-0.1.0.gem into system gems without network access" fullCmd="install:local" taksId="local" /></RakeGroup><RakeTask description="Create tag v0.1.0 and build and push event_loop-0.1.0.gem to Rubygems" fullCmd="release[remote]" taksId="release[remote]" /><RakeTask description="Run tests" fullCmd="test" taksId="test" /><RakeTask description="" fullCmd="default" taksId="default" /><RakeTask description="" fullCmd="release" taksId="release" /><RakeGroup description="" fullCmd="" taksId="release"><RakeTask description="" fullCmd="release:guard_clean" taksId="guard_clean" /><RakeTask description="" fullCmd="release:rubygem_push" taksId="rubygem_push" /><RakeTask description="" fullCmd="release:source_control_push" taksId="source_control_push" /></RakeGroup></RakeGroup></Settings>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Encoding">
4
+ <file url="PROJECT" charset="UTF-8" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,73 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="RUBY_MODULE" version="4">
3
+ <component name="FacetManager">
4
+ <facet type="gem" name="Ruby Gem">
5
+ <configuration>
6
+ <option name="GEM_APP_ROOT_PATH" value="$MODULE_DIR$" />
7
+ <option name="GEM_APP_TEST_PATH" value="$MODULE_DIR$/test" />
8
+ <option name="GEM_APP_LIB_PATH" value="$MODULE_DIR$/lib" />
9
+ </configuration>
10
+ </facet>
11
+ </component>
12
+ <component name="ModuleRunConfigurationManager">
13
+ <configuration default="false" name="loop_test" type="RubyRunConfigurationType" factoryName="Ruby" temporary="true">
14
+ <module name="event_loop" />
15
+ <RUBY_RUN_CONFIG NAME="RUBY_ARGS" VALUE="-e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift)" />
16
+ <RUBY_RUN_CONFIG NAME="WORK DIR" VALUE="$MODULE_DIR$/test/event_loop" />
17
+ <RUBY_RUN_CONFIG NAME="SHOULD_USE_SDK" VALUE="false" />
18
+ <RUBY_RUN_CONFIG NAME="ALTERN_SDK_NAME" VALUE="" />
19
+ <RUBY_RUN_CONFIG NAME="myPassParentEnvs" VALUE="true" />
20
+ <envs />
21
+ <EXTENSION ID="BundlerRunConfigurationExtension" bundleExecEnabled="false" />
22
+ <EXTENSION ID="JRubyRunConfigurationExtension" NailgunExecEnabled="false" />
23
+ <EXTENSION ID="RubyCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" track_test_folders="true" runner="rcov">
24
+ <COVERAGE_PATTERN ENABLED="true">
25
+ <PATTERN REGEXPS="/.rvm/" INCLUDED="false" />
26
+ </COVERAGE_PATTERN>
27
+ </EXTENSION>
28
+ <RUBY_RUN_CONFIG NAME="SCRIPT_PATH" VALUE="$MODULE_DIR$/test/event_loop/loop_test.rb" />
29
+ <RUBY_RUN_CONFIG NAME="SCRIPT_ARGS" VALUE="" />
30
+ <method />
31
+ </configuration>
32
+ <configuration default="false" name="test_exceptions_do_not_exit_loop: event_loop" type="TestUnitRunConfigurationType" factoryName="Test::Unit/Shoulda/Minitest" temporary="true">
33
+ <predefined_log_file id="RUBY_TESTUNIT" enabled="true" />
34
+ <module name="event_loop" />
35
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="RUBY_ARGS" VALUE="-e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift)" />
36
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="WORK DIR" VALUE="$MODULE_DIR$/test/event_loop" />
37
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="SHOULD_USE_SDK" VALUE="false" />
38
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="ALTERN_SDK_NAME" VALUE="" />
39
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="myPassParentEnvs" VALUE="true" />
40
+ <envs>
41
+ <env name="JRUBY_OPTS" value="-X+O" />
42
+ </envs>
43
+ <EXTENSION ID="BundlerRunConfigurationExtension" bundleExecEnabled="false" />
44
+ <EXTENSION ID="JRubyRunConfigurationExtension" NailgunExecEnabled="false" />
45
+ <EXTENSION ID="RubyCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" track_test_folders="true" runner="rcov">
46
+ <COVERAGE_PATTERN ENABLED="true">
47
+ <PATTERN REGEXPS="/.rvm/" INCLUDED="false" />
48
+ </COVERAGE_PATTERN>
49
+ </EXTENSION>
50
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="TESTS_FOLDER_PATH" VALUE="" />
51
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="TEST_SCRIPT_PATH" VALUE="$MODULE_DIR$/test/event_loop/loop_test.rb" />
52
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="TEST_FILE_MASK" VALUE="" />
53
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="TEST_METHOD_NAME" VALUE="test_exceptions_do_not_exit_loop" />
54
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="TEST_TEST_TYPE" VALUE="TEST_METHOD" />
55
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="DRB" VALUE="false" />
56
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="ZEUS" VALUE="false" />
57
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="SPRING" VALUE="false" />
58
+ <RTEST_RUN_CONFIG_SETTINGS_ID NAME="RUNNER_OPTIONS" VALUE="" />
59
+ <method />
60
+ </configuration>
61
+ </component>
62
+ <component name="NewModuleRootManager">
63
+ <content url="file://$MODULE_DIR$">
64
+ <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
65
+ <excludeFolder url="file://$MODULE_DIR$/.bundle" />
66
+ <excludeFolder url="file://$MODULE_DIR$/vendor/bundle" />
67
+ </content>
68
+ <orderEntry type="inheritedJdk" />
69
+ <orderEntry type="sourceFolder" forTests="false" />
70
+ <orderEntry type="library" scope="PROVIDED" name="minitest (v5.11.3, rbenv: 2.3.0) [gem]" level="application" />
71
+ <orderEntry type="library" scope="PROVIDED" name="rake (v10.4.2, rbenv: 2.3.0) [gem]" level="application" />
72
+ </component>
73
+ </module>
data/.idea/misc.xml ADDED
@@ -0,0 +1,14 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectLevelVcsManager" settingsEditedManually="false">
4
+ <OptionsSetting value="true" id="Add" />
5
+ <OptionsSetting value="true" id="Remove" />
6
+ <OptionsSetting value="true" id="Checkout" />
7
+ <OptionsSetting value="true" id="Update" />
8
+ <OptionsSetting value="true" id="Status" />
9
+ <OptionsSetting value="true" id="Edit" />
10
+ <ConfirmationsSetting value="0" id="Add" />
11
+ <ConfirmationsSetting value="0" id="Remove" />
12
+ </component>
13
+ <component name="ProjectRootManager" version="2" project-jdk-name="rbenv: 1.9.3-p545" project-jdk-type="RUBY_SDK" />
14
+ </project>
data/.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/event_loop.iml" filepath="$PROJECT_DIR$/.idea/event_loop.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
@@ -0,0 +1,43 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ChangeListManager">
4
+ <option name="TRACKING_ENABLED" value="true" />
5
+ <option name="SHOW_DIALOG" value="false" />
6
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
7
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
8
+ <option name="LAST_RESOLUTION" value="IGNORE" />
9
+ </component>
10
+ <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
11
+ <component name="CreatePatchCommitExecutor">
12
+ <option name="PATCH_PATH" value="" />
13
+ </component>
14
+ <component name="ProjectLevelVcsManager" settingsEditedManually="false">
15
+ <OptionsSetting value="true" id="Add" />
16
+ <OptionsSetting value="true" id="Remove" />
17
+ <OptionsSetting value="true" id="Checkout" />
18
+ <OptionsSetting value="true" id="Update" />
19
+ <OptionsSetting value="true" id="Status" />
20
+ <OptionsSetting value="true" id="Edit" />
21
+ <ConfirmationsSetting value="0" id="Add" />
22
+ <ConfirmationsSetting value="0" id="Remove" />
23
+ </component>
24
+ <component name="PropertiesComponent">
25
+ <property name="last_opened_file_path" value="$PROJECT_DIR$/.." />
26
+ </component>
27
+ <component name="ShelveChangesManager" show_recycled="false" />
28
+ <component name="TaskManager">
29
+ <task active="true" id="Default" summary="Default task">
30
+ <created>1525309363391</created>
31
+ <option name="number" value="Default" />
32
+ <updated>1525309363391</updated>
33
+ </task>
34
+ <servers />
35
+ </component>
36
+ <component name="VcsContentAnnotationSettings">
37
+ <option name="myLimit" value="2678400000" />
38
+ </component>
39
+ <component name="XDebuggerManager">
40
+ <breakpoint-manager />
41
+ <watches-manager />
42
+ </component>
43
+ </project>
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.0
5
+ before_install: gem install bundler -v 1.13.6
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at anehing@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in event_loop.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 anehing
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # EventLoop
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/event_loop`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'event_loop'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install event_loop
22
+
23
+ ## Usage
24
+
25
+ ```ruby
26
+ @event_loop = EventLoop::Loop.new
27
+
28
+ @event_loop.on(:event) do
29
+ # do some things
30
+ end
31
+ @event_loop.fire_every(5, :event)
32
+
33
+ @event_loop.run
34
+ end
35
+ ```
36
+ ## 描述
37
+ 使用IO.select作为阻塞方案,如果队里为空就用IO.select先阻塞.
38
+
39
+ ## Development
40
+
41
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
42
+
43
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
44
+
45
+ ## Contributing
46
+
47
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/event_loop. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
48
+
49
+
50
+ ## License
51
+
52
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
53
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "event_loop"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,31 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'event_loop/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "event_loop"
8
+ spec.version = EventLoop::VERSION
9
+ spec.authors = ["anehing"]
10
+ spec.email = ["anehing@gmail.com"]
11
+
12
+ spec.summary = "EventLoop"
13
+ # spec.description = %q{TODO: Write a longer description or delete this line.}
14
+ # spec.homepage = "TODO: Put your gem's website or public repo URL here."
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+
20
+
21
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
22
+ f.match(%r{^(test|spec|features)/})
23
+ end
24
+ spec.bindir = "exe"
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ["lib"]
27
+
28
+ spec.add_development_dependency "bundler", "~> 1.13"
29
+ spec.add_development_dependency "rake", "~> 10.0"
30
+ spec.add_development_dependency "minitest", "~> 5.0"
31
+ end
data/lib/event_loop.rb ADDED
@@ -0,0 +1,6 @@
1
+ require "event_loop/version"
2
+ require "event_loop/loop"
3
+ module EventLoop
4
+ # Your code goes here...
5
+
6
+ end
@@ -0,0 +1,184 @@
1
+ require 'logger'
2
+ module EventLoop
3
+ class Loop
4
+ class Timer
5
+ attr_reader :next_fire_time, :event, :interval, :last_fired_at
6
+
7
+ def initialize(interval, event, repeat=false)
8
+ @interval = interval
9
+ @event = event
10
+ @repeat = repeat
11
+ @started_at = Time.now
12
+ @last_fired_at = nil
13
+ reschedule
14
+ end
15
+
16
+ def reschedule
17
+ @next_fire_time = calculate_next_fire_time
18
+ end
19
+
20
+ def advance(amount)
21
+ @next_fire_time -= amount
22
+ end
23
+
24
+ def last_interval_start
25
+ @last_fired_at || @started_at
26
+ end
27
+
28
+ def calculate_next_fire_time
29
+ now = Time.now
30
+ return now if @interval == 0
31
+ fire_time = @last_fired_at || now
32
+ while fire_time <= now
33
+ fire_time += @interval
34
+ end
35
+ fire_time
36
+ end
37
+
38
+ def set_fired_time
39
+ @last_fired_at = Time.now
40
+ end
41
+
42
+ def due?(now=Time.now)
43
+ now >= @next_fire_time
44
+ end
45
+
46
+ def finished?
47
+ !@repeat && @last_fired_at
48
+ end
49
+ end
50
+
51
+ def initialize(logger = Logger.new(STDOUT))
52
+ @self_pipe_rd, @self_pipe_wr = IO.pipe
53
+ @event_queue = Queue.new
54
+ @stopped = false
55
+ @timers = {}
56
+ @logger = logger
57
+ @subscriptions = Hash.new { |h,k| h[k] = [] }
58
+ @subscriptions[:__add_timer] << Proc.new { |t| set_timer(t) }
59
+ @subscriptions[:__add_event] << Proc.new { |e, blk| @subscriptions[e] << blk }
60
+ end
61
+
62
+ def set_timer(timer)
63
+ existing_timer = @timers[timer.event]
64
+
65
+ if existing_timer
66
+ elapsed_interval = Time.now - existing_timer.last_interval_start
67
+ timer.advance(elapsed_interval)
68
+ end
69
+
70
+ @timers[timer.event] = timer
71
+
72
+ fire_timer(timer)
73
+ end
74
+
75
+ def next_timeout
76
+ return nil if @timers.empty?
77
+ timeout = @timers.values.map(&:next_fire_time).min - Time.now
78
+ timeout < 0 ? 0 : timeout
79
+ end
80
+
81
+ def stopped?
82
+ @stopped
83
+ end
84
+
85
+ def stop
86
+ @stopped = true
87
+ wakeup
88
+ end
89
+
90
+ def run
91
+ logger.debug "Running event loop"
92
+ while !stopped?
93
+ run_once
94
+ end
95
+ end
96
+
97
+ def run_once(nonblock=false)
98
+ wait_to_run(nonblock)
99
+
100
+ prune_timers
101
+ fire_timers
102
+
103
+ until @event_queue.empty?
104
+ evt, args = @event_queue.pop
105
+ dispatch_event(evt, args)
106
+ reschedule_timer_for_event(evt)
107
+ end
108
+ end
109
+
110
+ def wait_to_run(nonblock)
111
+ timeout = nonblock ? 0 : next_timeout
112
+ ready = IO.select([@self_pipe_rd], nil, nil, timeout)
113
+
114
+ if ready && ready[0] && ready[0][0] && ready[0][0] == @self_pipe_rd
115
+ @self_pipe_rd.read(1)
116
+ end
117
+ end
118
+
119
+ def fire_timers
120
+ @timers.each do |event, timer|
121
+ fire_timer(timer)
122
+ end
123
+ end
124
+
125
+ def fire_timer(timer)
126
+ if timer.due?
127
+ @event_queue << [timer.event]
128
+ timer.set_fired_time
129
+ end
130
+ end
131
+
132
+ def prune_timers
133
+ @timers.delete_if { |e, t| t.finished? }
134
+ end
135
+
136
+ def dispatch_event(event, args)
137
+ @logger.debug("EventLoop: Dispatching event '#{event}' with #{@subscriptions[event].size} callback(s).")
138
+
139
+ errors = []
140
+ @subscriptions[event].each do |s|
141
+ begin
142
+ s.call(*args)
143
+ rescue => e
144
+ errors << e
145
+ end
146
+ end
147
+
148
+ if !errors.empty?
149
+ @logger.error "#{errors.size} error(s) running task for event '#{event}' in Event Loop:"
150
+ end
151
+ end
152
+
153
+ def reschedule_timer_for_event(e)
154
+ @timers[e].reschedule if @timers[e]
155
+ end
156
+
157
+ def on(event, &blk)
158
+ fire(:__add_event, event, blk)
159
+ end
160
+
161
+ def fire(event, *args)
162
+ @event_queue << [event, args]
163
+ wakeup
164
+ end
165
+
166
+ def fire_every(interval, event)
167
+ @logger.debug "Firing event #{event} every #{interval} seconds."
168
+ fire(:__add_timer, Timer.new(interval, event, true))
169
+ end
170
+
171
+ def fire_after(interval, event)
172
+ @logger.debug "Firing event #{event} after #{interval} seconds."
173
+ fire(:__add_timer, Timer.new(interval, event, false))
174
+ end
175
+
176
+ def wakeup
177
+ begin
178
+ @self_pipe_wr.write_nonblock '.'
179
+ rescue Errno::EAGAIN
180
+ @logger.debug "Failed to wakeup event loop"
181
+ end
182
+ end
183
+ end
184
+ end
@@ -0,0 +1,3 @@
1
+ module EventLoop
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,106 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: event_loop
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - anehing
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-05-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.13'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.13'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ description:
56
+ email:
57
+ - anehing@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".idea/.rakeTasks"
64
+ - ".idea/encodings.xml"
65
+ - ".idea/event_loop.iml"
66
+ - ".idea/misc.xml"
67
+ - ".idea/modules.xml"
68
+ - ".idea/workspace.xml"
69
+ - ".travis.yml"
70
+ - CODE_OF_CONDUCT.md
71
+ - Gemfile
72
+ - LICENSE.txt
73
+ - README.md
74
+ - Rakefile
75
+ - bin/console
76
+ - bin/setup
77
+ - event_loop.gemspec
78
+ - lib/event_loop.rb
79
+ - lib/event_loop/loop.rb
80
+ - lib/event_loop/version.rb
81
+ homepage:
82
+ licenses:
83
+ - MIT
84
+ metadata: {}
85
+ post_install_message:
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ requirements: []
100
+ rubyforge_project:
101
+ rubygems_version: 2.5.1
102
+ signing_key:
103
+ specification_version: 4
104
+ summary: EventLoop
105
+ test_files: []
106
+ has_rdoc: