您的位置:首页 > 编程语言 > Go语言

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

2015-12-01 14:46 495 查看
一直在寻觅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       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, 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_ScheduleActive
msg.LParam = id
PostMThreadMsg(msg)
}

var g_scheduleManager *ScheduleManager

func init() {
g_scheduleManager = NewScheduleManager()
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: