You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This runs a maximum of 2 tasks concurrently. Total duration is 2 seconds (tasks 0,1 run first, then tasks 2,3).
74
74
75
-
### Queue-Based Resource Management
75
+
### Timeouts
76
76
77
-
Use a pre-populated queue of specific resources:
77
+
You can control how long to wait when acquiring resources using the `timeout` parameter. This is particularly useful when working with limited capacity limiters that might block indefinitely.
78
78
79
79
```ruby
80
80
require"async"
81
81
require"async/limiter"
82
-
require"async/queue"
83
82
84
83
Asyncdo
85
-
# Pre-populate queue with database connections
86
-
queue =Async::Queue.new
87
-
queue.push("connection_1")
88
-
queue.push("connection_2")
89
-
queue.push("connection_3")
84
+
# Zero limit will always block:
85
+
limiter =Async::Limiter::Limited.new(0)
90
86
91
-
limiter =Async::Limiter::Queued.new(queue)
92
-
93
-
5.times do |i|
94
-
limiter.async do |task|
95
-
# Automatically gets an available connection
96
-
limiter.acquire do |connection|
97
-
puts"Task #{i} using #{connection}"
98
-
task.sleep1
99
-
# Connection automatically returned to queue
100
-
end
101
-
end
102
-
end
87
+
limiter.acquire(timeout:3)
88
+
# => nil
89
+
90
+
limiter.acquire(timeout:3) do
91
+
puts"Acquired."
92
+
endorputs"Timed out!"
103
93
end
104
94
```
105
95
106
-
## Advanced Timeout Features
107
-
108
-
### Unified Timeouts
109
-
110
-
All acquisition methods support flexible timeout handling:
111
-
112
-
```ruby
113
-
limiter =Async::Limiter::Limited.new(1)
114
-
115
-
# Blocking (wait forever)
116
-
resource = limiter.acquire
117
-
118
-
# Non-blocking (immediate)
119
-
resource = limiter.acquire(timeout:0)
120
-
return"busy"unless resource
121
-
122
-
# Timed (wait up to 2.5 seconds)
123
-
resource = limiter.acquire(timeout:2.5)
124
-
return"timeout"unless resource
96
+
**Key timeout behaviors:**
125
97
126
-
# With blocks (automatic cleanup)
127
-
limiter.acquire(timeout:1.0) do |resource|
128
-
# Use resource
129
-
end# Automatically released
130
-
```
98
+
-`timeout: nil` (default) - Wait indefinitely until a resource becomes available
99
+
-`timeout: 0` - Non-blocking operation; return immediately if no resource is available
100
+
-`timeout: N` (where N > 0) - Wait up to N seconds for a resource to become available
131
101
132
-
## Rate Limiting with Timing Strategies
102
+
**Return values:**
103
+
- Returns `true` (or the acquired resource) when successful
104
+
- Returns `nil` when the timeout is exceeded or no resource is available
133
105
134
-
### Sliding Window Rate Limiting
106
+
## Rate Limiting
135
107
136
-
Continuous rolling time windows:
108
+
Timing strategies can be used to implement rate limiting, for example a continuous rolling time windows:
0 commit comments