在日常的在线客服系统运营中,有许多重复性的维护工作需要自动执行,比如保持连接活跃、定期更新凭证、发送提醒通知等。今天就来分享我们如何使用Golang的cron库来实现这些自动化定时任务。
在我们的客服系统中,存在三类需要定期执行的任务:
如果手动执行这些操作,不仅效率低下,还容易出错。定时任务帮我们实现了自动化运维。
Golang中有多个定时任务库,我们选择了github.com/robfig/cron
,因为它:
// 创建定时任务调度器
location, _ := time.LoadLocation("Asia/Shanghai")
cr := cron.New(cron.WithLocation(location))
// 添加定时任务,每分钟执行一次
cr.AddFunc("*/1 * * * *", func() {
log.Println("定时任务执行:", time.Now().Format("2006-01-02 15:04:05"), "给客服websocket链接发送ping")
ws.SendPingToKefuClient()
})
// 每天11点38分通知过期提醒
cr.AddFunc("38 11 * * *", func() {
log.Println("定时任务执行上午11点38分:", time.Now().Format("2006-01-02 15:04:05"), "通知客服账号过期提醒")
service.KefuExpireEmailNotice()
})
// 添加定时任务,每小时执行一次,更新抖音token
douyinClientKey := models.FindConfig("DouyinClientKey")
douyinClientSecret := models.FindConfig("DouyinClientSecret")
if douyinClientKey != "" && douyinClientSecret != "" {
cr.AddFunc("0 */1 * * *", func() {
log.Println("定时任务执行:", time.Now().Format("2006-01-02 15:04:05"), "更新抖音access_token,refresh_token")
service.UpdateDouyinAccessToken()
})
}
// 启动定时任务调度器
cr.Start()
defer cr.Stop()
cr.AddFunc("*/1 * * * *", func() {
ws.SendPingToKefuClient()
})
if douyinClientKey != "" && douyinClientSecret != "" {
cr.AddFunc("0 */1 * * *", func() {
service.UpdateDouyinAccessToken()
})
}
cr.AddFunc("38 11 * * *", func() {
service.KefuExpireEmailNotice()
})
cron.WithLocation
确保任务在正确时区执行
defer cr.Stop()
确保程序退出时任务正常停止
通过Golang的cron库,我们用不到50行代码就实现了三个重要的自动化运维任务:
这些定时任务大大减少了人工运维成本,提高了系统稳定性和用户体验。Golang的cron库简单易用,功能强大,是实现定时任务的优秀选择。
如果你也在开发需要定时任务的系统,不妨尝试一下这个方案!