Rafael Borja
Rafael Borja

Reputation: 4917

Safe fire and forget method in Perl

I need to execute a method (not process) asynchronously in my Perl code, but I must ensure that this code will never raise any exception and stop my main task execution.

What would be the best way to call a method asynchronously and silencing any potential exception whether it is the called method internal exception whether it is an threading exception?

In Java we would had something like this:

// my task runs here
try {
    // assyncrounous method invocation (fire and forget)
    new MyThread().start();
} catch (Throwable e) {
    // Silent any error
}
// my task continues here

Upvotes: 0

Views: 158

Answers (1)

ikegami
ikegami

Reputation: 386541

You have two options if you want to execute arbitrary code asynchronously: You can run it in a separate process, or you can run it in a separate thread. Using a separate process would make even more robust, but you could use a thread.

use threads;
my $thread = async { code() };

join the thread to wait for it to finish.

Upvotes: 1

Related Questions