让golang的cron库支持带事件参数的回调

来源:互联网 发布:网络诈骗在哪里报警 编辑:程序博客网 时间:2024/04/29 17:10

一直在寻觅c/c++下的cron库,可惜一直没找到。目前对我来说,cron可以做定时的某活动,比如晚上八点怎么怎么的,golang下有大神提供的cron库,那么这部分的实现还是放到go实现的服务器下面吧,然后再通知别的服务器,只能绕路子了。


go下的cron库使用的是 github.com/robfig/cron,最终使用的是 github.com/jakecoffman/cron,后者也是前者的改进版,主要增加了个RemoveJob的函数来移除特定的任务。


主要使用中的不变就是自带的回调为一个func(),无任何参数,所以被激活的时候无法判断到底是哪个计划任务被调度了,写多个函数也比较麻烦,于是看看是否能修改下源码来完成这个功能。后来看了下代码,原来不用修改代码就可以实现,设计的还是不错的,只要实现一个Job的interface就可以了,那么动手吧。


type Job interface {Run()}

我们的目标就是实现这个接口,cron库自带的一个封装就是直接把func() type成这个类型,然后实现Run这个函数。我们这里麻烦点,定义成

type SchduleActiveCallback func(int)type ScheduleJob struct {id       intcallback 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_ScheduleActivemsg.LParam = idPostMThreadMsg(msg)}

千万记得回调是在别的routine里的,别忘记同步了。


于是大概的整体实现就像下面一样,反正大概能实现需求就行了,回调的时候带了个id,就可以知道是哪个job被调用了

package mainimport ("github.com/jakecoffman/cron""shareutils""strconv")type SchduleActiveCallback func(int)type ScheduleJob struct {id       intcallback 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, scheduleExpr string) {job := NewScheduleJob(id, this._scheduleActive)this.cronJob.AddJob(scheduleExpr, job, 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_ScheduleActivemsg.LParam = idPostMThreadMsg(msg)}var g_scheduleManager *ScheduleManagerfunc init() {g_scheduleManager = NewScheduleManager()}


0 0
原创粉丝点击