Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #230 Timeout

Cancel an ongoing processing p if it has not finished after 5s.

require 'timeout'
Timeout::timeout(5) { p }
def main(p) do
  p
  |> Task.async()
  |> Task.await()
end
import "context"
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
p(ctx)
uses Process;
var
  P: TProcess;
begin
  ...
  P.Execute;
  if not P.WaitOnExit(5000) then P.Terminate(0);
end.
use Coro;
my $p = Coro->new( sub { ... } );
$p->ready;

my $start = time;
for (1..100) {
    cede;
    if ( (time - $start) > 5 ) {
        $p->cancel;        
        last;
    }
}

New implementation...
< >
programming-idioms.org