Create a gist now

Instantly share code, notes, and snippets.

@yuntan /chan2.go
Last active Dec 3, 2015

What would you like to do?
HaskellでGoぽく定期実行
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Starting...")
ch := time.After(3 * time.Second)
<-ch
fmt.Println("Started")
ch = time.Tick(3 * time.Second)
for _ = range ch {
fmt.Println("3")
}
}
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
import Control.Monad (forever)
delay :: Int -> IO ()
delay = threadDelay . (* 1000000)
after :: Int -> IO (Chan ())
after time = do
ch <- newChan
_ <- forkIO $ delay time >> writeChan ch ()
return ch
tick :: Int -> IO (Chan ())
tick time = do
ch <- newChan
_ <- forkIO $ forever $ delay time >> writeChan ch ()
return ch
main :: IO ()
main = do
putStrLn "Starting..."
after 3 >>= readChan
putStrLn "Started"
ch' <- tick 3
forever $ readChan ch' >> putStrLn "3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment