Skip to content

Commit 622446f

Browse files
committed
Watcher: No need to keep checking mtimes if already stale
1 parent c4a3ee0 commit 622446f

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

lib/spring/watcher/polling.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,12 @@ def start
2525
@poller = Thread.new {
2626
Thread.current.abort_on_exception = true
2727

28-
loop do
28+
until stale?
2929
Kernel.sleep latency
3030
check_stale
3131
end
32+
33+
@poller = nil
3234
}
3335
end
3436
end

test/unit/watcher_test.rb

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,48 @@ class PollingWatcherTest < Spring::Test::WatcherTest
66
def watcher_class
77
Spring::Watcher::Polling
88
end
9+
10+
test "skips staleness checks if already stale" do
11+
class << watcher
12+
attr_reader :checked_when_stale_count
13+
attr_reader :checked_when_not_stale_count
14+
15+
def check_stale
16+
@checked_when_stale_count = 0 unless defined? @checked_when_stale_count
17+
@checked_when_not_stale_count = 0 unless defined? @checked_when_not_stale_count
18+
19+
if stale?
20+
@checked_when_stale_count += 1
21+
else
22+
@checked_when_not_stale_count += 1
23+
end
24+
25+
super
26+
end
27+
end
28+
29+
# Track when we're marked as stale.
30+
on_stale_count = 0
31+
watcher.on_stale { on_stale_count += 1 }
32+
33+
# Add a file to watch and start polling.
34+
file = "#{@dir}/omg"
35+
touch file, Time.now - 2.seconds
36+
watcher.add file
37+
watcher.start
38+
39+
# First touch bumps mtime and marks as stale.
40+
touch file, Time.now - 1.second
41+
Timeout.timeout(1) { sleep 0.01 until on_stale_count > 0 }
42+
assert_equal 0, watcher.checked_when_stale_count
43+
assert_equal 1, watcher.checked_when_not_stale_count
44+
assert_equal 1, on_stale_count
45+
46+
# Second touch skips mtime check because it's already stale.
47+
touch file, Time.now
48+
sleep 1
49+
assert_equal 0, watcher.checked_when_stale_count
50+
assert_equal 1, watcher.checked_when_not_stale_count
51+
assert_equal 1, on_stale_count
52+
end
953
end

0 commit comments

Comments
 (0)