上网查了下相关资料,基本上都介绍的是github.com\robfig\cron这个包来执行定时任务,试了下确实可以执行。但是此包下没有删 除任务的方法,只有暂停的方法(Stop),若要停止之前的任务只执行新定义的任务,除非服务器重启再定义新任务。后来又参考了一下其他人的建议,采用了 github.com\jakecoffman\cron这个包。后者是在前者的基础上做了一定的修改,给每个任务添加的一个新属性Name,然后新添加 一个remove(name)方法,用来删除指定名字的任务,经测试使用后可正常删除任务,只不过之前的计划任务名得新建一个全局变量来存储。

以下先简单介绍下定义时间集合的信息:

字段名 是否必须 允许的值 允许的特定字符
秒(Seconds) 0-59
* / , -
分(Minutes) 0-59
* / , -
时(Hours) 0-23
* / , -
日(Day of month) 1-31
* / , – ?
月(Month) 1-12 or JAN-DEC
* / , -
星期(Day of week) 0-6 or SUM-SAT
* / , – ?

注:
1)月(Month)和星期(Day of week)字段的值不区分大小写,如:SUN、Sun 和 sun 是一样的。
2)星期
(Day of week)字段如果没提供,相当于是 *

2、特殊字符说明
1)星号(*)
表示 cron 表达式能匹配该字段的所有值。如在第5个字段使用星号(month),表示每个月

回到顶部
2)斜线(/)
表示增长间隔,如第1个字段(minutes) 值是 3-59/15,表示每小时的第3分钟开始执行一次,之后每隔 15 分钟执行一次(即 3、18、33、48 这些时间点执行),这里也可以表示为:3/15

回到顶部
3)逗号(,)
用于枚举值,如第6个字段值是 MON,WED,FRI,表示 星期一、三、五 执行

回到顶部
4)连字号(-)
表示一个范围,如第3个字段的值为 9-17 表示 9am 到 5pm 直接每个小时(包括9和17)

回到顶部
5)问号(?)
只用于 日(Day of month) 和 星期(Day of week),表示不指定值,可以用于代替 *

在beego下使用,我简单的封装一下(代码不是我写的,而且写的很随意,也只保证了可用的程度),自定义package jobs如下:

job.go源码:

  1. package jobs
  2. import (
  3. "github.com/astaxie/beego"
  4. "github.com/jakecoffman/cron"
  5. "reflect"
  6. "runtime/debug"
  7. "sync"
  8. "sync/atomic"
  9. )
  10. type Job struct {
  11. Name    string
  12. inner   cron.Job
  13. status  uint32
  14. running sync.Mutex
  15. }
  16. const UNNAMED = "(unnamed)"
  17. func New(job cron.Job) *Job {
  18. name := reflect.TypeOf(job).Name()
  19. if name == "Func" {
  20. name = UNNAMED
  21. }
  22. return &Job{
  23. Name:  name,
  24. inner: job,
  25. }
  26. }
  27. func (j *Job) Status() string {
  28. if atomic.LoadUint32(&j.status) > 0 {
  29. return "RUNNING"
  30. }
  31. return "IDLE"
  32. }
  33. func (j *Job) Run() {
  34. // If the job panics, just print a stack trace.
  35. // Don't let the whole process die.
  36. defer func() {
  37. if err := recover(); err != nil {
  38. beego.Error("%v", debug.Stack())
  39. }
  40. }()
  41. if !selfConcurrent {
  42. j.running.Lock()
  43. defer j.running.Unlock()
  44. }
  45. if workPermits != nil {
  46. workPermits <- struct{}{}
  47. defer func() { <-workPermits }()
  48. }
  49. atomic.StoreUint32(&j.status, 1)
  50. defer atomic.StoreUint32(&j.status, 0)
  51. j.inner.Run()
  52. }

jobrunner.go源码:

  1. // A job runner for executing scheduled or ad-hoc tasks asynchronously from HTTP requests.
  2. //
  3. // It adds a couple of features on top of the cron package to make it play nicely with Revel:
  4. // 1. Protection against job panics.  (They print to ERROR instead of take down the process)
  5. // 2. (Optional) Limit on the number of jobs that may run simulatenously, to
  6. //    limit resource consumption.
  7. // 3. (Optional) Protection against multiple instances of a single job running
  8. //    concurrently.  If one execution runs into the next, the next will be queued.
  9. // 4. Cron expressions may be defined in app.conf and are reusable across jobs.
  10. // 5. Job status reporting.
  11. package jobs
  12. import (
  13. //"fmt"
  14. "github.com/jakecoffman/cron"
  15. "time"
  16. )
  17. // Callers can use jobs.Func to wrap a raw func.
  18. // (Copying the type to this package makes it more visible)
  19. //
  20. // For example:
  21. //    jobs.Schedule("cron.frequent", jobs.Func(myFunc))
  22. type Func func()
  23. func (r Func) Run() { r() }
  24. //定时执行任务
  25. func Schedule(spec string, job cron.Job, name string) error {
  26. sched := cron.Parse(spec)
  27. /*if err != nil {
  28. return err
  29. }*/
  30. MainCron.Schedule(sched, New(job), name)
  31. return nil
  32. }
  33. // Run the given job at a fixed interval.
  34. // The interval provided is the time between the job ending and the job being run again.
  35. // The time that the job takes to run is not included in the interval.
  36. func Every(duration time.Duration, job cron.Job, name string) {
  37. MainCron.Schedule(cron.Every(duration), New(job), name)
  38. }
  39. // Run the given job right now.
  40. func Now(job cron.Job) {
  41. go New(job).Run()
  42. }
  43. // Run the given job once, after the given delay.
  44. func In(duration time.Duration, job cron.Job) {
  45. go func() {
  46. time.Sleep(duration)
  47. New(job).Run()
  48. }()
  49. }
  50. // 暂停所有任务
  51. func Stop() {
  52. MainCron.Stop()
  53. }
  54. //清空任务
  55. func Remove(name string) {
  56. MainCron.RemoveJob(name)
  57. }

plugin.go源码:

  1. package jobs
  2. import (
  3. "github.com/jakecoffman/cron"
  4. )
  5. const DEFAULT_JOB_POOL_SIZE = 10
  6. var (
  7. // Singleton instance of the underlying job scheduler.
  8. MainCron *cron.Cron
  9. // This limits the number of jobs allowed to run concurrently.
  10. workPermits chan struct{}
  11. // Is a single job allowed to run concurrently with itself?
  12. selfConcurrent bool
  13. )
  14. func init() {
  15. MainCron = cron.New()
  16. workPermits = make(chan struct{}, DEFAULT_JOB_POOL_SIZE)
  17. selfConcurrent = false
  18. MainCron.Start()
  19. }

因为是网站执行定时任务,这边我是将任务是否开启的控制权放在前端页面,通过点击按钮访问controller方法,从而启动任务,所以我把任务执行方法放在了controller中。通过如下方式调用:

  1. import (
  2. //其他引用包我都省略了
  3. "hnnaserver/src/jobs"
  4. )
  5. type job struct {
  6. user     string
  7. province int64
  8. method   int64
  9. count    int64
  10. }
  11. //任务执行的方法
  12. func (j *job) Run() {
  13. //do something....
  14. }
  15. func (this *SystemController) AutoDisCus() {
  16. spec := "0 0 15 * * 1-5"//定义执行时间点 参照上面的说明可知 执行时间为 周一至周五每天15:00:00执行
  17. //spec := "*/5 * * * * ?" //这是网上一般的例子 即每5s执行一次
  18. j := &job{user, province, method, count}
  19. jobs.Schedule(spec, j, taskName) //3个参数分别为 执行时间(规则之间介绍过) 要执行的任务  任务名
  20. }

若要删除某项任务,则调用remove方法即可,如下:

    1. jobs.Remove(tasksName)

最新文章

  1. UI第六节——UINavigationController 详解
  2. 复制过来的东西也不靠谱,微信公众号第三方平台的API
  3. sasscore学习之_mixin.scss
  4. [原创]java WEB学习笔记84:Hibernate学习之路-- -映射 一对一关系 ,基外键的方式实现
  5. hive-初看hive
  6. Webdriver:Unsupported Marionette protocol version 2, required 3
  7. Bzoj 1976: [BeiJing2010组队]能量魔方 Cube 最小割,最大流
  8. C# 事件的理解
  9. Nuc900 bsp turbowriter使用注意点
  10. 解决本地访问Android文档是非常慢的问题
  11. Decorators and Wrappers in Python
  12. UVA 311 Packets 贪心+模拟
  13. 2016NEFU集训第n+3场 D - Bicycle Race
  14. Screen tearing
  15. SQL关键字转换大写核心算法实现
  16. bzoj 4605: 崂山白花蛇草水
  17. NOIWC2018 游记
  18. BZOJ_1712_[Usaco2007 China]Summing Sums 加密_矩阵乘法
  19. 2015 Benelux Algorithm Programming Contest I- Interesting Integers
  20. linux常用命令总结-&gt;1

热门文章

  1. 过滤器Filter(拦截jsp页面的跳转)案例:
  2. C# PDF添加水印
  3. 测试-Unity修改权重
  4. Java中的类加载器
  5. linux下报错处理经验
  6. 2016年12月4日 星期日 --出埃及记 Exodus 20:25
  7. js实现元素边框闪烁功能
  8. #查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素
  9. oracle 快照
  10. Cheatsheet: 2013 10.09 ~ 10.23