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") }

  

 

posted @ 2021-05-07 10:12  -零  阅读(260)  评论(0编辑  收藏  举报