每秒打印一次,并且在 Perl 6 中使用 react 时每 5 秒睡眠 10 秒? [英] print sth every second, and also sleep 10 seconds very 5 seconds using react ... whenever in Perl 6?

查看:96
本文介绍了每秒打印一次,并且在 Perl 6 中使用 react 时每 5 秒睡眠 10 秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每秒打印当前时间,也想睡10秒非常5秒:

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;
    }
}

输出不是我想要的:

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

我想要的是这个:

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

不太了解PromiseSupply...关于Raku,这可能吗?

Don't know much about Promise, Supply... about Raku, 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();
}   

给出如下输出:

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

这将绝对确保您在 10 秒暂停之间获得 5 滴答声;使用两个单独的间隔供应来做它 - 就像这里的许多解决方案一样 - 不会对此提供任何严格的保证,并且可能会不时错过一个滴答声.(没有的那个是带有 rotor 的可爱的,如果您不需要实际打印sleep done"的话,这是一个不错的选择).它也没有状态(变量)和条件,这是相当不错的.

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.

虽然这看起来可能是递归的,但由于 when 是一个异步循环结构,它实际上根本不会建立调用堆栈.

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.

它也是完全由异步结构构建的,因此在 Perl 6.d 中,如果 react 在线程池上被触发,它不会阻塞真正的 OS 线程.所以你可以有成千上万的这些活动.相比之下,sleep 将阻塞一个真正的线程,这是 sleep 传统上应该做的,但如果处理异步构造,则不太适合.

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.

这篇关于每秒打印一次,并且在 Perl 6 中使用 react 时每 5 秒睡眠 10 秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆