-
-
Notifications
You must be signed in to change notification settings - Fork 92
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add
Scheduler#load
and Async::Idler
for scheduling tasks when idle.
`Async::Idler` introduces a `maximum_load` and functions like a semaphore, in that it will schedule tasks until the maximum load is reached.
- Loading branch information
Showing
4 changed files
with
72 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# frozen_string_literal: true | ||
|
||
# Released under the MIT License. | ||
# Copyright, 2024, by Samuel Williams. | ||
|
||
module Async | ||
class Idler | ||
def initialize(maximum_load = 0.8, backoff: 0.01, parent: nil) | ||
@maximum_load = maximum_load | ||
@backoff = backoff | ||
@parent = parent | ||
end | ||
|
||
def async(*arguments, parent: (@parent or Task.current), **options, &block) | ||
wait | ||
|
||
# It is crucial that we optimistically execute the child task, so that we prevent a tight loop invoking this method from consuming all available resources. | ||
parent.async(*arguments, **options, &block) | ||
end | ||
|
||
def wait | ||
scheduler = Fiber.scheduler | ||
backoff = nil | ||
|
||
while scheduler.load > @maximum_load | ||
if backoff | ||
sleep(backoff) | ||
backoff *= 2.0 | ||
else | ||
scheduler.yield | ||
backoff = @backoff | ||
end | ||
end | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters