gitea源码

schedule_spec.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package actions
  4. import (
  5. "context"
  6. "strings"
  7. "time"
  8. "code.gitea.io/gitea/models/db"
  9. repo_model "code.gitea.io/gitea/models/repo"
  10. "code.gitea.io/gitea/modules/timeutil"
  11. "github.com/robfig/cron/v3"
  12. )
  13. // ActionScheduleSpec represents a schedule spec of a workflow file
  14. type ActionScheduleSpec struct {
  15. ID int64
  16. RepoID int64 `xorm:"index"`
  17. Repo *repo_model.Repository `xorm:"-"`
  18. ScheduleID int64 `xorm:"index"`
  19. Schedule *ActionSchedule `xorm:"-"`
  20. // Next time the job will run, or the zero time if Cron has not been
  21. // started or this entry's schedule is unsatisfiable
  22. Next timeutil.TimeStamp `xorm:"index"`
  23. // Prev is the last time this job was run, or the zero time if never.
  24. Prev timeutil.TimeStamp
  25. Spec string
  26. Created timeutil.TimeStamp `xorm:"created"`
  27. Updated timeutil.TimeStamp `xorm:"updated"`
  28. }
  29. // Parse parses the spec and returns a cron.Schedule
  30. // Unlike the default cron parser, Parse uses UTC timezone as the default if none is specified.
  31. func (s *ActionScheduleSpec) Parse() (cron.Schedule, error) {
  32. parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)
  33. schedule, err := parser.Parse(s.Spec)
  34. if err != nil {
  35. return nil, err
  36. }
  37. // If the spec has specified a timezone, use it
  38. if strings.HasPrefix(s.Spec, "TZ=") || strings.HasPrefix(s.Spec, "CRON_TZ=") {
  39. return schedule, nil
  40. }
  41. specSchedule, ok := schedule.(*cron.SpecSchedule)
  42. // If it's not a spec schedule, like "@every 5m", timezone is not relevant
  43. if !ok {
  44. return schedule, nil
  45. }
  46. // Set the timezone to UTC
  47. specSchedule.Location = time.UTC
  48. return specSchedule, nil
  49. }
  50. func init() {
  51. db.RegisterModel(new(ActionScheduleSpec))
  52. }
  53. func UpdateScheduleSpec(ctx context.Context, spec *ActionScheduleSpec, cols ...string) error {
  54. sess := db.GetEngine(ctx).ID(spec.ID)
  55. if len(cols) > 0 {
  56. sess.Cols(cols...)
  57. }
  58. _, err := sess.Update(spec)
  59. return err
  60. }