go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/cron/job_invocation.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package cron 9 10 import ( 11 "context" 12 "crypto/rand" 13 "encoding/hex" 14 "time" 15 ) 16 17 func newJobInvocation(jobName string) *JobInvocation { 18 return &JobInvocation{ 19 ID: newRandomID(), 20 Status: JobInvocationStatusIdle, 21 JobName: jobName, 22 Finished: make(chan struct{}), 23 } 24 } 25 26 func newRandomID() string { 27 uuid := make([]byte, 16) 28 _, _ = rand.Read(uuid) 29 uuid[6] = (uuid[6] & 0x0f) | 0x40 // set version 4 30 uuid[8] = (uuid[8] & 0x3f) | 0x80 // set variant 2 31 return hex.EncodeToString(uuid) 32 } 33 34 // JobInvocation is metadata for a job invocation (or instance of a job running). 35 type JobInvocation struct { 36 ID string `json:"id"` 37 JobName string `json:"jobName"` 38 39 Started time.Time `json:"started"` 40 Complete time.Time `json:"complete"` 41 Err error `json:"err"` 42 43 Parameters JobParameters `json:"parameters"` 44 Status JobInvocationStatus `json:"status"` 45 State interface{} `json:"-"` 46 47 Cancel context.CancelFunc `json:"-"` 48 Finished chan struct{} `json:"-"` 49 } 50 51 // Elapsed returns the elapsed time for the invocation. 52 func (ji JobInvocation) Elapsed() time.Duration { 53 if !ji.Complete.IsZero() { 54 return ji.Complete.Sub(ji.Started) 55 } 56 if !ji.Started.IsZero() { 57 return Now().Sub(ji.Started) 58 } 59 return 0 60 } 61 62 // Clone clones the job invocation. 63 func (ji JobInvocation) Clone() *JobInvocation { 64 return &JobInvocation{ 65 ID: ji.ID, 66 JobName: ji.JobName, 67 68 Started: ji.Started, 69 Complete: ji.Complete, 70 Err: ji.Err, 71 72 Parameters: ji.Parameters, 73 Status: ji.Status, 74 State: ji.State, 75 76 Cancel: ji.Cancel, 77 Finished: ji.Finished, 78 } 79 }