Executing a function with a timeout

前端 未结 6 738
醉梦人生
醉梦人生 2020-12-14 19:30

What would be an idiomatic way of executing a function within a time limit? Something like,

(with-timeout 5000
 (do-somthing))

Unless do-so

6条回答
  •  隐瞒了意图╮
    2020-12-14 19:44

    It's a quite a breeze using clojure's channel facilities https://github.com/clojure/core.async

    require respective namespace

    (:require [clojure.core.async :refer [>! alts!! timeout chan go]])
    

    the function wait takes a timeout [ms], a function [f] and optional parameters [args]

    (defn wait [ms f & args]
      (let [c (chan)]
        (go (>! c (apply f args)))
        (first (alts!! [c (timeout ms)]))))
    

    third line pops off the call to f to another thread. fourth line consumes the result of the function call or (if faster) the timeout.

    consider the following example calls

    (wait 1000 (fn [] (do (Thread/sleep 100) 2)))
    => 2
    

    but

    (wait 50 (fn [] (do (Thread/sleep 100) 2)))
    => nil
    

提交回复
热议问题