Closed
Description
As far as I understand the logic behind the TimerTask, it should run a job every execution seconds and kill it if it running too long.
The current logic is a little bit different. It causes a job to be run execution seconds after it did the previous iteration.
Short example. If I need to poll something every 30 seconds. I'll create a timer task with execution_interval set to 30 and say timeout set to 15 seconds. My code is polling a slow thing which can reply in 20 seconds or more.
What I expect:
0:00 Poll
0:10 Poll finished
0:30 Poll
0:45 Poll finished
1:00 Poll
1:05 Poll finished
1:30 Poll
1:35 Poll finished
...
What really happens with TimerTask:
0:00 Poll
0:10 Poll finished
0:40 Poll
0:55 Poll finished
1:25 Poll
1:30 Poll finished
2:00 Poll
2:05 Poll finished
...
Now TimerTask doesn't look like a good candidate for polling.
#!/usr/bin/env ruby
require "concurrent"
puts "Creating tasks"
10.times do |x|
task = Concurrent::TimerTask.new(run_now: true, execution_interval: 20) do
sleep x*2
puts "#{Time.now} #{x*2} finished"
end
task.execute
end
sleep 60
puts "Terminated"
The output:
Creating tasks
2017-10-19 01:41:48 +0300 0 finished
2017-10-19 01:41:50 +0300 2 finished
2017-10-19 01:41:52 +0300 4 finished
2017-10-19 01:41:54 +0300 6 finished
2017-10-19 01:41:56 +0300 8 finished
2017-10-19 01:41:58 +0300 10 finished
2017-10-19 01:42:00 +0300 12 finished
2017-10-19 01:42:02 +0300 14 finished
2017-10-19 01:42:04 +0300 16 finished
2017-10-19 01:42:06 +0300 18 finished
2017-10-19 01:42:08 +0300 0 finished
2017-10-19 01:42:12 +0300 2 finished
2017-10-19 01:42:16 +0300 4 finished
2017-10-19 01:42:20 +0300 6 finished
2017-10-19 01:42:24 +0300 8 finished
2017-10-19 01:42:28 +0300 0 finished
2017-10-19 01:42:28 +0300 10 finished
2017-10-19 01:42:32 +0300 12 finished
2017-10-19 01:42:34 +0300 2 finished
2017-10-19 01:42:36 +0300 14 finished
2017-10-19 01:42:40 +0300 4 finished
2017-10-19 01:42:40 +0300 16 finished
2017-10-19 01:42:44 +0300 18 finished
2017-10-19 01:42:46 +0300 6 finished
2017-10-19 01:42:48 +0300 0 finished
Terminated
Consider the increasing intervals.
- Operating system: linux
concurrent-ruby
version: 1.0.5concurrent-ruby-ext
installed: noconcurrent-ruby-edge
used: no