Gaucheでインターバルタイマ

30分プログラム、その349。gauche.threadsを使って、インターバルタイマを作ってみる。

インターバルタイマは、

gosh> (add-interval! 10 (cut print "hello"))

とすると10秒ごとに"hello"と出力されるようなタイマ。JavascriptのsetIntervalを思い出すといいと思う。

使い方

;; タイマの設定
gosh> (define id (add-interval! 1 (cut print "hello")))
id

hello
hello
hello
hello
hello
hello
hello
hello

;; タイマの削除
gosh> (del-interval! id)
((1 . #<thread #f terminated 0x41ecc0>))

ソースコード

#! /opt/local/bin/gosh
;; -*- mode:scheme; coding:utf-8 -*-
;;
;; interval.scm -
;;
;; Copyright(C) 2008 by mzp
;; Author: MIZUNO Hiroki / mzpppp at gmail dot com
;; http://howdyworld.org
;;
;; Timestamp: 2008/08/17 23:10:55
;;
;; This program is free software; you can redistribute it and/or
;; modify it under MIT Lincence.
;;

(use srfi-1)
(use gauche.threads)

(define make-id
  (let1 id 0
    (lambda ()
      (set! id (+ id 1))
      id)))

(define *intervals* '())
(define (add-interval! interval f)
  (let ([t (make-thread (lambda () 
			  (while #t
			    (thread-sleep! interval)
			    (f))))]
	[id (make-id)])
    (thread-start! t)
    (push! *intervals* (cons id t))
    id))

(define (del-interval! id)
  (let1 t (assoc id *intervals*)
    (thread-terminate! (cdr t))
    (delete! id 
	     *intervals* 
	     (lambda (x y) (eqv? x (car y))))))