Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

定时器回调函数增加参数传递 #7

Closed
wants to merge 2 commits into from

Conversation

utopiaprince
Copy link

给jobItem增加参数元素,作为定时器的传递参数,类似同样的定时器回调函数作为协程来处理;

@alex023
Copy link
Owner

alex023 commented Sep 29, 2018

感谢提交,定时器的回调函数通常都不直接带参数。如果需要,可以考虑由函数闭包来封装。比如这样:

import (
	"fmt"
	"github.com/alex023/clock"
	"time"
)
func main() {
	var (
		myClock = clock.NewClock()
		count   int
		jobFunc = func(maxCount int) func() {
			return func() {
				if count < maxCount {
					count++
					fmt.Println("do ", count)
				}
			}
		}
	)
	//创建任务,间隔0.01秒,执行一次
	myClock.AddJobRepeat(time.Millisecond*10, 100, jobFunc(10))

	//等待2秒观察输出,尽管允许执行100次,但函数只会有10条输出
	time.Sleep(2 * time.Second)
}

这样,无论参数多少个,都可以适应。go的语法虽然啰嗦点,但闭包是非常好用的。
不知道我的描述是否解决了你的问题,期待反馈!

@utopiaprince
Copy link
Author

非常感谢,之前接触的都是嵌入式方面的,类似解决方案都是用参数传递的方法,在golang里没有想到有这种方法。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants