一个信号量与定时器的例子(Golang)

        程序可用来定时执行一些任务,并通过信号量处理,在被强制中断时,也能做相应警告及清理处理.  

package main

//信号量与定时器
//author: Xiong Chuan Liang
//date: 2015-2-25

import "fmt"
import "os"
import "os/signal"
import "time"

func main() {

	sigs := make(chan os.Signal, 1)
	done := make(chan bool, 1)

	signal.Notify(sigs, os.Interrupt, os.Kill)

	go func() {
		sig := <-sigs
		switch sig {
		case os.Interrupt:
			fmt.Println("signal: Interrupt")
		case os.Kill:
			fmt.Println("signal: Kill")
		default:
			fmt.Println("signal: Others")
		}
		done <- true
	}()

	fmt.Println("awaiting signal")

	//main()....
	go JobTicker(done)
	<-done
	close(done)
	//app.Exit()
	fmt.Println("exiting")
}

func JobTicker(done <-chan bool) {
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-done:
			return
		case <-ticker.C:
			fmt.Println("job......")
		}
	}
}


如果按 ctrl-C 则结果如下:

awaiting signal
job......
job......
signal: Interrupt
interrupt
exiting


Go by Example: Signals:    https://gobyexample.com/signals


MAIL: [email protected]

Blog: http://blog.csdn.net/xcl168

  



你可能感兴趣的:(定时器,go语言,Signal,time.NewTicker)