在 Clojure 中定期调用函数 [英] Periodically calling a function in Clojure

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

问题描述

我正在寻找一种在 Clojure 中定期调用函数的非常简单的方法.

I'm looking for a very simple way to call a function periodically in Clojure.

JavaScript 的 setInterval 有我想要的那种 API.如果我在 Clojure 中重新构想它,它看起来像这样:

JavaScript's setInterval has the kind of API I'd like. If I reimagined it in Clojure, it'd look something like this:

(def job (set-interval my-callback 1000))

; some time later...

(clear-interval job)

出于我的目的,我不介意这是否会创建一个新线程、在线程池中运行或其他什么.时间是否准确也不是关键.事实上,提供的时间段(以毫秒为单位)可能只是一个调用完成结束和下一个调用开始之间的延迟.

For my purposes I don't mind if this creates a new thread, runs in a thread pool or something else. It's not critical that the timing is exact either. In fact, the period provided (in milliseconds) can just be a delay between the end of one call completing and the commencement of the next.

推荐答案

Clojure 还有不少调度库:(从简单到非常高级)

There's also quite a few scheduling libraries for Clojure: (from simple to very advanced)

直接来自 at-at 的 github 主页示例:

Straight from the examples of the github homepage of at-at:

(use 'overtone.at-at)
(def my-pool (mk-pool))
(let [schedule (every 1000 #(println "I am cool!") my-pool)]
  (do stuff while schedule runs)
  (stop schedule))

使用 (每 1000 #(println "I am cool!") my-pool :fixed-delay true) 如果你想在任务结束和下一个开始之间延迟一秒,而不是在两次开始之间.

Use (every 1000 #(println "I am cool!") my-pool :fixed-delay true) if you want a delay of a second between end of task and start of next, instead of between two starts.

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

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