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.

import "context"
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
p(ctx)
def main(p) do
  p
  |> Task.async()
  |> Task.await()
end
import static java.lang.Thread.sleep;
Thread p = new Thread(() -> {});
p.start();
p.join(5_000);
p.interrupt();
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;
    }
}
require 'timeout'
Timeout::timeout(5) { p }
use tokio::time::{timeout, Duration};
timeout(Duration::from_secs(5), p()).await;

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