Skip to content

Commit 18c4d12

Browse files
authored
Merge pull request #20 from jeremy/stop-listening-when-stale
Watcher: if we're already stale, no need to keep listening for changes
2 parents 229ff1e + 4cb49f2 commit 18c4d12

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/spring/watcher/listen.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ class Listen < Abstract
2323

2424
attr_reader :listener
2525

26+
def initialize(*)
27+
super
28+
@listener = nil
29+
end
30+
2631
def start
2732
return if defined?(@listener) && @listener
2833

@@ -37,6 +42,10 @@ def stop
3742
end
3843
end
3944

45+
def running?
46+
@listener && @listener.processing?
47+
end
48+
4049
def subjects_changed
4150
return unless defined?(@listener)
4251
return unless @listener.respond_to?(:directories)
@@ -56,6 +65,14 @@ def changed(modified, added, removed)
5665
end
5766
end
5867

68+
def mark_stale
69+
super
70+
71+
# May be called from listen thread which won't be happy
72+
# about stopping itself, so stop from another thread.
73+
Thread.new { stop }.join
74+
end
75+
5976
def base_directories
6077
([root] +
6178
files.keys.reject { |f| f.start_with? "#{root}/" }.map { |f| File.expand_path("#{f}/..") } +

test/unit_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,22 @@ def watcher_class
5555
FileUtils.rm_rf other_dir_2
5656
end
5757
end
58+
59+
test "stops listening when already stale" do
60+
# Track when we're marked as stale.
61+
on_stale_count = 0
62+
watcher.on_stale { on_stale_count += 1 }
63+
64+
# Add a file to watch and start listening.
65+
file = "#{@dir}/omg"
66+
touch file, Time.now - 2.seconds
67+
watcher.add file
68+
watcher.start
69+
assert watcher.running?
70+
71+
# Touch bumps mtime and marks as stale which stops listener.
72+
touch file, Time.now - 1.second
73+
Timeout.timeout(1) { sleep 0.1 while watcher.running? }
74+
assert_equal 1, on_stale_count
75+
end
5876
end

0 commit comments

Comments
 (0)