让golang的cron库支持带事件参数的回调
发布时间:2020-12-16 18:36:38 所属栏目:大数据 来源:网络整理
导读:一直在寻觅c/c++下的cron库,可惜一直没找到。目前对我来说,cron可以做定时的某活动,比如晚上八点怎么怎么的,golang下有大神提供的cron库,那么这部分的实现还是放到go实现的服务器下面吧,然后再通知别的服务器,只能绕路子了。 go下的cron库使用的是git
一直在寻觅c/c++下的cron库,可惜一直没找到。目前对我来说,cron可以做定时的某活动,比如晚上八点怎么怎么的,golang下有大神提供的cron库,那么这部分的实现还是放到go实现的服务器下面吧,然后再通知别的服务器,只能绕路子了。
主要使用中的不变就是自带的回调为一个func(),无任何参数,所以被激活的时候无法判断到底是哪个计划任务被调度了,写多个函数也比较麻烦,于是看看是否能修改下源码来完成这个功能。后来看了下代码,原来不用修改代码就可以实现,设计的还是不错的,只要实现一个Job的interface就可以了,那么动手吧。
type Job interface { Run() } 我们的目标就是实现这个接口,cron库自带的一个封装就是直接把func() type成这个类型,然后实现Run这个函数。我们这里麻烦点,定义成 type SchduleActiveCallback func(int) type ScheduleJob struct { id int callback SchduleActiveCallback }
然后实现Run方法 func (this *ScheduleJob) Run() { if nil != this.callback { this.callback(this.id) } else { shareutils.LogErrorln("Invalid callback function") } } 剩下就简单啦,不要使用AddFunc这个函数,使用AddJob这个函数,将我们实现的Job扔进去就Ok啦。 func (this *ScheduleManager) AddJob(id int,scheduleExpr string) { job := NewScheduleJob(id,this._scheduleActive) this.cronJob.AddJob(scheduleExpr,job,strconv.Itoa(id)) } func (this *ScheduleManager) _scheduleActive(id int) { shareutils.LogDebugln("Job active:",id) msg := &MThreadMsg{} msg.Event = kMThreadMsg_ScheduleActive msg.LParam = id PostMThreadMsg(msg) } 千万记得回调是在别的routine里的,别忘记同步了。
于是大概的整体实现就像下面一样,反正大概能实现需求就行了,回调的时候带了个id,就可以知道是哪个job被调用了 package main import ( "github.com/jakecoffman/cron" "shareutils" "strconv" ) type SchduleActiveCallback func(int) type ScheduleJob struct { id int callback SchduleActiveCallback } func NewScheduleJob(_id int,_job SchduleActiveCallback) *ScheduleJob { instance := &ScheduleJob{ id: _id,callback: _job,} return instance } func (this *ScheduleJob) Run() { if nil != this.callback { this.callback(this.id) } else { shareutils.LogErrorln("Invalid callback function") } } type ScheduleManager struct { cronJob *cron.Cron } func NewScheduleManager() *ScheduleManager { instance := &ScheduleManager{} instance.cronJob = cron.New() return instance } func (this *ScheduleManager) Start() { this.cronJob.Start() } func (this *ScheduleManager) Stop() { this.cronJob.Stop() } func (this *ScheduleManager) AddJob(id int,strconv.Itoa(id)) } func (this *ScheduleManager) RemoveJob(id int) { this.cronJob.RemoveJob(strconv.Itoa(id)) } func (this *ScheduleManager) _scheduleActive(id int) { shareutils.LogDebugln("Job active:",id) msg := &MThreadMsg{} msg.Event = kMThreadMsg_ScheduleActive msg.LParam = id PostMThreadMsg(msg) } var g_scheduleManager *ScheduleManager func init() { g_scheduleManager = NewScheduleManager() } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |