As we can see, each example() function is called in order, but depending on the randomly generated value, it will return out-of-order, having run concurrently.

Note: If we were to remove the Async { ... } code around 5.times { ... }, we would see the script run sequentially. This is because async can be utilized by non-async code, though not providing any performance benefits if not async aware (within a Async::Reactor).

Step 3

Asynchronous tasks can take arbitrary amounts of time, and often we want to limit the execution time to a given timeout value.

We can adjust our previous script.rb to include a timeout of 0.5 seconds.

Source Code

require 'async'
# example function that takes a random ammount of time to complete
# now with a timeout
def example(id)
Async do |task|
task.with_timeout(0.5) do
value = rand # get random value
puts "Putting #{id} to sleep for #{value} seconds."
task.sleep(value)
puts "#{id} woke up!"
rescue Async::TimeoutError
puts "#{id} timed out!"
end
end
end
# asynchronously run five example functions
Async do
5.times do |index|
example(index)
end
end

Debugging Scenarios

Help

Katacoda offerings an Interactive Learning Environment for Developers. This course uses a command line and a pre-configured sandboxed environment for you to use. Below are useful commands when working with the environment.

cd <directory>

Change directory

ls

List directory

echo 'contents' > <file>

Write contents to a file

cat <file>

Output contents of file

Vim

In the case of certain exercises you will be required to edit files or text. The best approach is with Vim. Vim has two different modes, one for entering commands (Command Mode) and the other for entering text (Insert Mode). You need to switch between these two modes based on what you want to do. The basic commands are: