在 Clojure 中定期执行代码 [英] Executing code at regularly timed intervals in Clojure

查看:15
本文介绍了在 Clojure 中定期执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Clojure 中让代码定期运行的最佳方法是什么?我目前正在使用 java.util.concurrent.ScheduledExecutorService,但那是 Java - 是否有一种 Clojure 方式来安排代码定期运行,延迟后,可取消?我见过的所有 Clojure 代码示例都使用 Thread/sleep,这似乎也太 Java 了.

解决方案

Overtone 的源代码非常值得一看

a>,特别是 代码,用于在特定时间安排事件时间.

这是一个音乐合成系统,所以你必须希望他们有正确的计时码!!

此外,他们还帮助将计时代码分离到一个单独的项目中 (overtone/at-at) 以便您可以根据需要轻松导入它.这为底层 Java 库提供了一个很好的 Clojure 包装器(即 ScheduledThreadPoolExecutor 和朋友们).语法是这样的:

<代码>;;每 500 毫秒运行一些函数(每 500 个功能)

您还可以在特定时间安排活动:

<代码>;;从现在起 10 秒后运行其他功能(at (+ 10000 (now)) some-other-function)

What's the best way to make code run at regular intervals in Clojure ? I'm currently using java.util.concurrent.ScheduledExecutorService, but that's Java - is there a Clojure way of scheduling code to run at regular intervals, after a delay, cancellably ? All the Clojure code examples I've seen use Thread/sleep, which also seems too Java.

解决方案

Well worth looking at the source code for Overtone, in particular the code for scheduling events at a particular time.

It's a music synthesis system so you have to hope they have the timing code right!!

Also they have helpfully separated the timing code out into a separate project (overtone/at-at) so that you can easily import it if you want. This provides a nice Clojure wrapper to the underlying Java libraries (i.e. ScheduledThreadPoolExecutor and friends). The syntax is like this:

;; run some-function every 500ms
(every 500 some-function)

You can also shedule events at specific times:

;; run some-other-function 10 seconds from now
(at (+ 10000 (now)) some-other-function)

这篇关于在 Clojure 中定期执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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