print sth every second, and also sleep 10 seconds very 5 seconds using react … whenever in Perl 6?

  • A+
Category:Languages

I want to print the current time every second, and also want to sleep 10 seconds very 5 seconds:

react {     whenever Supply.interval(1) {         say DateTime.now.posix;     }      whenever Supply.interval(5) {         sleep 10;         say 'Sleep Done';     }      whenever signal(SIGINT) {         say "Done.";         done;     } } 

the output is not what i wanted:

1542371045 Sleep Done 1542371055 Sleep Done 1542371065 Sleep Done 1542371075 Done. ... 

what i want is this:

1542371045 1542371046 1542371047 1542371048 1542371049  Sleep Done 1542371059 1542371060 1542371061   1542371062  1542371063          Sleep Done Done. 

Don't know much about Promise, Supply... about Perl 6, is this possible?

 


Depending on exactly what else was needed, I'd probably write it something like this:

react {     sub sequence() {         whenever Supply.interval(1).head(5) {             say DateTime.now.posix;             LAST whenever Promise.in(10) {                 say "Sleep done";                 sequence();             }         }     }     sequence(); }    

Which gives output like this:

1542395158 1542395159 1542395160 1542395161 1542395162 Sleep done 1542395172 1542395173 1542395174 1542395175 1542395176 Sleep done 1542395186 1542395187 1542395188 ... 

This will make absolutely sure you get 5 ticks out between the 10s pauses; doing it with two separate interval supplies - as in many solutions here - will not give any strict guarantees of that, and could miss a tick now and then. (One that doesn't is the cute one with rotor, which is a good bet if you don't need to actually print the "sleep done" thing). It's also free of state (variables) and conditions, which is rather nice.

While this looks like it might be recursive, since whenever is an asynchronous looping construct, it will not actually build up a call stack at all.

It's also fully built of asynchronous constructs, and so in Perl 6.d will not - if the react is triggered on the thread pool - ever block a real OS thread. So you could have thousands of these active. By contrast, sleep will block a real thread, which is what sleep traditionally would be expected to do, but isn't such a good fit if otherwise dealing with asynchronous constructs.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: