Go異步check簡單示例

 

 

異步check代碼:

package main

import (
	"fmt"
	"reflect"
	"time"
)

type janitor struct {
	interval time.Duration
	overtime time.Duration
}


func (j *janitor) Runasyncheck(f interface{}, params ...interface{}) {
	//fmt.Println(params)
	//創建週期斷續器
	ticker := time.NewTicker(j.interval)
	//創建定時器
	timer := time.NewTimer(j.overtime)
	loop:
		for {
			select {
			case <-timer.C: //當Timer每次到達設置的時間時就會向管道發送消息,此時超時退出
				print("超時\n")
				break loop
			case <-ticker.C: //當Ticker每次到達設置的時間時就會向管道發送消息,此時進行異步check操作
				//print("異步check\n")
				fv := reflect.ValueOf(f)
				realParams := make([]reflect.Value, len(params)) //參數
				for i, item := range params {
					realParams[i] = reflect.ValueOf(item)
				}
				fv.Call(realParams)
			}
		}
	fmt.Println("Break")
}

測試:


package main

import ( "fmt" "time" "testing" ) func hello1() { fmt.Println("123") } func hello2(i string) { fmt.Println(i) } func Test_main(t *testing.T){ j := &janitor{ interval: time.Second, overtime:5*time.Second, } j.Runasyncheck(hello1) j.Runasyncheck(hello2,"23") }

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章