Skip to content

Instantly share code, notes, and snippets.

@christianromney
Created July 17, 2013 21:08
Show Gist options
  • Save christianromney/6024513 to your computer and use it in GitHub Desktop.
Save christianromney/6024513 to your computer and use it in GitHub Desktop.
(ns circuito.core
(:require [clojure.core.async :as async :refer :all])
(:gen-class))
(def ^:dynamic *timeout* 300)
;; Like defn, but executes body in a go block, allowing at most *timeout* milliseconds for completion
(defmacro defcommand [name args & body]
`(defn ~name ~args
(let [t# (timeout *timeout*)
c# (chan)]
(go (>! c# (do ~@body)))
(<!! (go
(let [[r# ch#] (alts! [t# c#])]
(if (= ch# t#) :timeout r#)))))))
(defcommand fetch-url
[url]
(slurp url))
(defn- to-int
"Tries to coerce a value to an integer"
[val]
(when val
(cond (integer? val) val
(number? val) (int val)
(string? val) (int (Integer/parseInt val)))))
(defn -main
"Fetch the URL in the first arg in second arg (or default) milliseconds"
[& args]
(let [uri (first args)
t (or (to-int (second args)) *timeout*)]
(binding [*timeout* t]
(println
(fetch-url uri)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment