utils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package publish
  2. import (
  3. "log"
  4. "os"
  5. "time"
  6. "github.com/qor/oss"
  7. "gorm.io/gorm"
  8. )
  9. const (
  10. schedulePublishJobNamePrefix = "schedule-publisher"
  11. listPublishJobNamePrefix = "list-publisher"
  12. )
  13. func RunPublisher(db *gorm.DB, storage oss.StorageInterface, publisher *Builder) {
  14. { // schedule publisher
  15. scheduleP := NewSchedulePublishBuilder(publisher)
  16. for name, model := range NonVersionPublishModels {
  17. name := name
  18. model := model
  19. go RunJob(schedulePublishJobNamePrefix+"-"+name, time.Minute, time.Minute*5, func() {
  20. if err := scheduleP.Run(model); err != nil {
  21. log.Printf("schedule publisher error: %v\n", err)
  22. }
  23. })
  24. }
  25. for name, model := range VersionPublishModels {
  26. name := name
  27. model := model
  28. go RunJob(schedulePublishJobNamePrefix+"-"+name, time.Minute, time.Minute*5, func() {
  29. if err := scheduleP.Run(model); err != nil {
  30. log.Printf("schedule publisher error: %v\n", err)
  31. }
  32. })
  33. }
  34. }
  35. { // list publisher
  36. listP := NewListPublishBuilder(db, storage)
  37. for name, model := range ListPublishModels {
  38. name := name
  39. model := model
  40. go RunJob(listPublishJobNamePrefix+"-"+name, time.Minute, time.Minute*5, func() {
  41. if err := listP.Run(model); err != nil {
  42. log.Printf("schedule publisher error: %v\n", err)
  43. }
  44. })
  45. }
  46. }
  47. }
  48. func RunJob(jobName string, interval time.Duration, timeout time.Duration, f func()) {
  49. second := 1
  50. ticker := time.NewTicker(interval)
  51. defer ticker.Stop()
  52. for now := range ticker.C {
  53. targetTime := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute()+1, second, 0, now.Location())
  54. time.Sleep(targetTime.Sub(now))
  55. start := time.Now()
  56. done := make(chan struct{})
  57. go func() {
  58. defer func() {
  59. stop := time.Now()
  60. log.Printf("job_name: %s, started_at: %s, stopped_at: %s, time_spent_ms: %d\n", jobName, start, stop, int64(stop.Sub(start)/time.Millisecond))
  61. }()
  62. f()
  63. done <- struct{}{}
  64. }()
  65. select {
  66. case <-done:
  67. case <-time.After(timeout):
  68. log.Printf("job_name: %s, started_at: %s, timeout: %s\n", jobName, start, time.Now())
  69. os.Exit(124)
  70. }
  71. }
  72. }