class JoobQ::Timeout::TimeoutError

Overview

The Timeout class in the JoobQ module provides a mechanism to execute a block of code with a specified timeout. If the block takes longer than the specified timeout to complete, it raises a Timeout::TimeoutError.

Properties

Methods

run

def self.run(timeout : Time::Span, &block : ->)

Executes the given block with a timeout. If the block takes longer than the specified timeout (in seconds) to complete, it raises a Timeout::TimeoutError.

Usage

Executing a Block with a Timeout

To execute a block of code with a timeout, use the run method:

begin
  JoobQ::Timeout.run(5.seconds) do
    # Your code here
    sleep 10 # Simulate a long-running task
  end
rescue JoobQ::Timeout::TimeoutError
  puts "The block exceeded the timeout!"
end

Workflow

  1. Initialization:
  1. Executing the Block:
  1. Enforcing the Timeout:
  1. Checking Completion:

Example

Here is a complete example demonstrating how to use the Timeout class:

require "joobq"

begin
  JoobQ::Timeout.run(5.seconds) do
    puts "Starting a task..."
    sleep 10 # Simulate a long-running task
    puts "Task completed!"
  end
rescue JoobQ::Timeout::TimeoutError
  puts "The block exceeded the timeout!"
end

This example attempts to execute a block that sleeps for 10 seconds with a timeout of 5 seconds. Since the block exceeds the timeout, a Timeout::TimeoutError is raised, and the message "The block exceeded the timeout!" is printed.

Defined in:

joobq/timeout.cr