Created
June 6, 2019 08:30
-
-
Save fskale/b032a6f34c0700e70498b61c05466696 to your computer and use it in GitHub Desktop.
Write delayed but non-blocking to STDOUT using Mojolicious ! (E.g. progress to STDOUT)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use Mojo::Base -strict; | |
use Mojo::IOLoop::Stream; | |
use Mojo::IOLoop::Delay; | |
use Mojo::ByteStream 'b'; | |
# Create stream | |
my $stream = Mojo::IOLoop::Stream->new(\*STDOUT)->timeout(0); | |
my $text | |
= b( | |
q{DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT DAS IST EIN TESTTEXT} | |
)->split(qr/\s+/)->to_array; | |
$stream->on( | |
close => sub { | |
my $stream = shift; | |
printf(STDERR "\nSTREAM CLOSED !\n"); | |
CORE::exit(0); | |
} | |
); | |
$stream->on( | |
error => sub { | |
my ($stream, $err) = @_; | |
printf(STDERR "STREAM ERROR: %s\n", $err); | |
$stream->stop; | |
$stream->close; | |
CORE::exit(1); | |
} | |
); | |
# Start and stop watching for new data | |
$stream->start; | |
#create delay loop | |
my $delay = Mojo::IOLoop::Delay->new; | |
#must be global scope ! | |
my $write; | |
$write = sub { | |
my $t = shift(@{$text}) // ($stream->stop and $stream->close and return); | |
$delay->steps( | |
sub { | |
my $d = shift; | |
Mojo::IOLoop->timer(0.3 => $d->begin); | |
$stream->write(sprintf("%s ", $t)); | |
}, | |
sub { | |
$write->(); | |
} | |
)->wait; | |
}; | |
$write->(); | |
# Start reactor if necessary | |
$stream->reactor->start unless $stream->reactor->is_running; | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment