“–————人與人之間還是直接點好——————”
package main
import (
"fmt"
"math/rand"
"os"
"os/signal"
"syscall"
"time"
)
const defaultInterval = time.Duration(time.Second * 5) //5秒一次
type timer struct {
Interval time.Duration
//任類型通道
Ch chan struct{}
}
type msg struct {
Rid uint32
Timestamp int64
}
func Newbeats() *msg {
return &msg{
Rid: rand.Uint32(),
Timestamp: time.Now().Unix(),
}
}
func (t *timer) StartBeat() {
t.stop() //並不能停止定時器,程序結束時才停止
go func() {、
//建議點進去看看這個函數
ticker := time.NewTicker(t.Interval)
for {
select { //select函數是等待通道的參數,根據通道是否有輸出進行執行
case <-t.Ch: //如果ch通道成功讀取數據,則執行該case處理語句
ticker.Stop() //停止通道並不是關閉通道,以防止併發goroutine
return //結束程序,即結束定時器
case <-ticker.C:
}
dd := Newbeats()
fmt.Printf("=== %s\n", dd)
}
}()
}
func (t *timer) stop() {
//通道有東西便停止通道,並不是關閉定時器
if t.Ch != nil {
close(t.Ch)
t.Ch = nil
}
}
func main() {
//1 創建一個信號
c := make(chan os.Signal, 1)
//2 選擇監聽的內容
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
//開始定時器
Plugin.StartBeat()
//3 只有接到監聽的信息才結束程序
<-c
}
//創建實例的第二種方式,直接創建一個變量
//創建一個實例,可以被其它調用 xxx.Plugin.StartBeat()
var Plugin *timer = &timer{
Interval: defaultInterval,
}