Skip to content

Commit

Permalink
fix(timer): ensure channel is closed once timer fires
Browse files Browse the repository at this point in the history
  • Loading branch information
stakach committed May 25, 2021
1 parent d6612e8 commit b4501cd
Showing 1 changed file with 27 additions and 13 deletions.
40 changes: 27 additions & 13 deletions src/tasker/timer.cr
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,39 @@ class Timer

def start_timer : Nil
Log.trace { "timer start called, id: #{self.object_id}" }
spawn(same_thread: true) do
Log.trace { "timer waiting for #{@sleep_for} seconds, id: #{self.object_id}" }
select
when @cancel.receive
Log.trace { "timer cancelled, id: #{self.object_id}" }
when timeout(@sleep_for.seconds)
Log.trace { "timer fired, id: #{self.object_id}" }
@cancelled = true
@callback.call
end
end
spawn(same_thread: true) { schedule_wait }
Fiber.yield
end

def cancel : Nil
return if @cancelled
Log.trace { "timer cancel requested, id: #{self.object_id}" }
@cancelled = true
@cancel.send(true)
Fiber.yield
begin
@cancel.send(true)
rescue
end
end

private def schedule_wait
Log.trace { "timer waiting for #{@sleep_for} seconds, id: #{self.object_id}" }

select
when @cancel.receive
Log.trace { "timer cancelled, id: #{self.object_id}" }
when timeout(@sleep_for.seconds)
if !@cancelled
Log.trace { "timer fired, id: #{self.object_id}" }
@cancelled = true
@callback.call
else
Log.trace { "timer fired but ignored as cancelled, id: #{self.object_id}" }
end
end
rescue error
Log.warn(exception: error) { "error in tasker scheduler" }
ensure
@cancelled = true
@cancel.close
end
end

0 comments on commit b4501cd

Please sign in to comment.