···170170 return err
171171}
172172173173-// CancelRunningJobs cancels all running and waiting jobs associated with a specific workflow.
174174-func CancelRunningJobs(ctx context.Context, repoID int64, ref, workflowID string) error {
175175- // Find all runs in the specified repository, reference, and workflow with statuses 'Running' or 'Waiting'.
173173+// CancelPreviousJobs cancels all previous jobs of the same repository, reference, workflow, and event.
174174+// It's useful when a new run is triggered, and all previous runs needn't be continued anymore.
175175+func CancelPreviousJobs(ctx context.Context, repoID int64, ref, workflowID string, event webhook_module.HookEventType) error {
176176+ // Find all runs in the specified repository, reference, and workflow with non-final status
176177 runs, total, err := db.FindAndCount[ActionRun](ctx, FindRunOptions{
177177- RepoID: repoID,
178178- Ref: ref,
179179- WorkflowID: workflowID,
180180- Status: []Status{StatusRunning, StatusWaiting},
178178+ RepoID: repoID,
179179+ Ref: ref,
180180+ WorkflowID: workflowID,
181181+ TriggerEvent: event,
182182+ Status: []Status{StatusRunning, StatusWaiting, StatusBlocked},
181183 })
182184 if err != nil {
183185 return err
+5
models/actions/run_list.go
···1010 repo_model "code.gitea.io/gitea/models/repo"
1111 user_model "code.gitea.io/gitea/models/user"
1212 "code.gitea.io/gitea/modules/container"
1313+ webhook_module "code.gitea.io/gitea/modules/webhook"
13141415 "xorm.io/builder"
1516)
···7172 WorkflowID string
7273 Ref string // the commit/tag/… that caused this workflow
7374 TriggerUserID int64
7575+ TriggerEvent webhook_module.HookEventType
7476 Approved bool // not util.OptionalBool, it works only when it's true
7577 Status []Status
7678}
···9799 }
98100 if opts.Ref != "" {
99101 cond = cond.And(builder.Eq{"ref": opts.Ref})
102102+ }
103103+ if opts.TriggerEvent != "" {
104104+ cond = cond.And(builder.Eq{"trigger_event": opts.TriggerEvent})
100105 }
101106 return cond
102107}
+20
models/actions/schedule.go
···5566import (
77 "context"
88+ "fmt"
89 "time"
9101011 "code.gitea.io/gitea/models/db"
···118119119120 return committer.Commit()
120121}
122122+123123+func CleanRepoScheduleTasks(ctx context.Context, repo *repo_model.Repository) error {
124124+ // If actions disabled when there is schedule task, this will remove the outdated schedule tasks
125125+ // There is no other place we can do this because the app.ini will be changed manually
126126+ if err := DeleteScheduleTaskByRepo(ctx, repo.ID); err != nil {
127127+ return fmt.Errorf("DeleteCronTaskByRepo: %v", err)
128128+ }
129129+ // cancel running cron jobs of this repository and delete old schedules
130130+ if err := CancelPreviousJobs(
131131+ ctx,
132132+ repo.ID,
133133+ repo.DefaultBranch,
134134+ "",
135135+ webhook_module.HookEventSchedule,
136136+ ); err != nil {
137137+ return fmt.Errorf("CancelPreviousJobs: %v", err)
138138+ }
139139+ return nil
140140+}