Skip to content

Commit

Permalink
add timeout job to limit execution time
Browse files Browse the repository at this point in the history
  • Loading branch information
arriven committed Apr 4, 2022
1 parent 21206e1 commit 33e0d0e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/job/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,12 @@ func Get(t string) Job {
return checkJob
case "sleep":
return sleepJob
case "loop":
return loopJob
case "discard-error":
return discardErrorJob
case "timeout":
return timeoutJob
case "loop":
return loopJob
case "encrypted":
return encryptedJob
default:
Expand Down
26 changes: 26 additions & 0 deletions src/job/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,32 @@ func discardErrorJob(ctx context.Context, logger *zap.Logger, globalConfig *Glob
return data, nil
}

func timeoutJob(ctx context.Context, logger *zap.Logger, globalConfig *GlobalConfig, args config.Args) (
data any, err error, //nolint:unparam // data is here to match Job
) {
var jobConfig struct {
BasicJobConfig

Timeout time.Duration
Job config.Config
}

if err := ParseConfig(&jobConfig, args, *globalConfig); err != nil {
return nil, fmt.Errorf("error parsing job config: %w", err)
}

ctx, cancel := context.WithTimeout(ctx, jobConfig.Timeout)
defer cancel()

job := Get(jobConfig.Job.Type)

if job == nil {
return nil, fmt.Errorf("unknown job %q", jobConfig.Job.Type)
}

return job(ctx, logger, globalConfig, jobConfig.Job.Args)
}

func loopJob(ctx context.Context, logger *zap.Logger, globalConfig *GlobalConfig, args config.Args) (data any, err error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
Expand Down

0 comments on commit 33e0d0e

Please sign in to comment.