You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cron.go 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package cron
  6. import (
  7. "context"
  8. "time"
  9. "code.gitea.io/gitea/modules/graceful"
  10. "code.gitea.io/gitea/modules/sync"
  11. "github.com/gogs/cron"
  12. )
  13. var c = cron.New()
  14. // Prevent duplicate running tasks.
  15. var taskStatusTable = sync.NewStatusTable()
  16. // NewContext begins cron tasks
  17. // Each cron task is run within the shutdown context as a running server
  18. // AtShutdown the cron server is stopped
  19. func NewContext() {
  20. initBasicTasks()
  21. initExtendedTasks()
  22. lock.Lock()
  23. for _, task := range tasks {
  24. if task.IsEnabled() && task.DoRunAtStart() {
  25. go task.Run()
  26. }
  27. }
  28. c.Start()
  29. started = true
  30. lock.Unlock()
  31. graceful.GetManager().RunAtShutdown(context.Background(), func() {
  32. c.Stop()
  33. lock.Lock()
  34. started = false
  35. lock.Unlock()
  36. })
  37. }
  38. // TaskTableRow represents a task row in the tasks table
  39. type TaskTableRow struct {
  40. Name string
  41. Spec string
  42. Next time.Time
  43. Prev time.Time
  44. ExecTimes int64
  45. }
  46. // TaskTable represents a table of tasks
  47. type TaskTable []*TaskTableRow
  48. // ListTasks returns all running cron tasks.
  49. func ListTasks() TaskTable {
  50. entries := c.Entries()
  51. eMap := map[string]*cron.Entry{}
  52. for _, e := range entries {
  53. eMap[e.Description] = e
  54. }
  55. lock.Lock()
  56. defer lock.Unlock()
  57. tTable := make([]*TaskTableRow, 0, len(tasks))
  58. for _, task := range tasks {
  59. spec := "-"
  60. var (
  61. next time.Time
  62. prev time.Time
  63. )
  64. if e, ok := eMap[task.Name]; ok {
  65. spec = e.Spec
  66. next = e.Next
  67. prev = e.Prev
  68. }
  69. task.lock.Lock()
  70. tTable = append(tTable, &TaskTableRow{
  71. Name: task.Name,
  72. Spec: spec,
  73. Next: next,
  74. Prev: prev,
  75. ExecTimes: task.ExecTimes,
  76. })
  77. task.lock.Unlock()
  78. }
  79. return tTable
  80. }