timeouter

Version, currently 0.34 versions

github.com/kostya/timeouter

Simple timeouter

7 stars
0 dependents
License: MIT

Nothing has been indexed for 0.3 yet. The tag is recorded, its shard.yml has not been read, so the manifest and dependency list below are empty because they are unknown rather than because they are absent.

Installation

# Add this to your shard.yml
dependencies:
  timeouter:
    github: kostya/timeouter
    version: ~> 0.3

Then run:

shards install

shard.yml

No shard.yml has been indexed for 0.3. You can read it on the repository.

Dependencies

Unknown: the shard.yml for this version has not been read yet.

README

This README is the one indexed from the repository at its latest ref, not from the tag for this version.

# Timeouter

Simple timeouter for crystal lang. Uses one coroutine, which triggered with precision interval. Also it avoid crystal memory leak with many coroutines: https://github.com/crystal-lang/crystal/issues/3333

## Installation

Add this to your application's `shard.yml`:

```yaml
dependencies:
  timeouter:
    github: kostya/timeouter
```

## Usage

```crystal
require "timeouter"

# set precision, 1 second by default
Timeouter.precision = 0.5.seconds

# spend 1.5.second
Timeouter.after(1.5.seconds).receive
```

## Helper: receive from Channel with timeout

```crystal
require "timeouter"

ch1 = Channel(Int32).new
ch2 = Channel(Int32).new

spawn do
  sleep 2.0
  ch1.send(1)
end

spawn do
  sleep 0.5
  ch2.send(2)
end

p Timeouter.receive_with_timeout(ch1, 1.seconds) # => nil
p Timeouter.receive_with_timeout(ch2, 1.seconds) # => 2
```

## Helper: send to Channel with timeout

```crystal
require "timeouter"

ch1 = Channel(Int32).new
ch2 = Channel(Int32).new

spawn do
  sleep 2.0
  p ch1.receive
end

spawn do
  sleep 0.5
  p ch2.receive
end

Timeouter.send_with_timeout(ch1, 1, 1.seconds) # => nil
Timeouter.send_with_timeout(ch2, 2, 1.seconds) # => true

# 2
```

## Receive from channel with timeout manually
```crystal
require "timeouter"

channel = Channel(Int32).new
after = Timeouter.after(1.0.seconds)

spawn do
  sleep 10.0
  channel.send(1)
end

t = Time.now

select
when result = channel.receive
# Cancel timeouter manyally
#   it also would be cancel automatically
#   but this is remove it fast from scheduler
#   which allow less cpu usage
  after.close

  p result
when after.receive
  p :timeouted
end

p Time.now - t

# => :timeouted
# => 1.000
```