Logo

Programming-Idioms

# 230 Timeout
Cancel an ongoing processing p if it has not finished after 5s.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
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)
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;