Skip to content

Commit

Permalink
add example for panic handler
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnRoesler committed Jun 6, 2022
1 parent f294b9b commit 8e88b6b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
14 changes: 13 additions & 1 deletion example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gocron_test

import (
"fmt"
"log"
"time"

"github.com/go-co-op/gocron"
Expand Down Expand Up @@ -202,7 +203,7 @@ func ExampleScheduler_ChangeLocation() {

location, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
panic(err)
log.Fatalf("Error loading location: %s", err)
}
s.ChangeLocation(location)
fmt.Println(s.Location())
Expand Down Expand Up @@ -805,3 +806,14 @@ func ExampleScheduler_Weeks() {

_, _ = s.Every(2).Weeks().Monday().Wednesday().Friday().Do(task)
}

// ---------------------------------------------------------------------
// ---------------------OTHER-FUNCTIONS---------------------------------
// ---------------------------------------------------------------------

func ExampleSetPanicHandler() {
gocron.SetPanicHandler(func(jobName string, recoverData interface{}) {
fmt.Printf("Panic in job: %s", jobName)
fmt.Println("do something to handle the panic")
})
}
9 changes: 5 additions & 4 deletions gocron.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import (
"time"
)

// Panic handler type for external programs to use
// PanicHandlerFunc represents a type that can be set to handle panics occurring
// during job execution.
type PanicHandlerFunc func(jobName string, recoverData interface{})

// The global panic handler
Expand All @@ -25,10 +26,10 @@ var (
panicHandlerMutex = sync.RWMutex{}
)

// SetPanicHandler sets the global panichandler to the given function.
// Setting it to nil disables automatic panic handling.
// SetPanicHandler sets the global panicHandler to the given function.
// Leaving it nil or setting it to nil disables automatic panic handling.
// If the panicHandler is not nil, any panic that occurs during executing a job will be recovered
// and the panicHandler func will be called with the job's name and the recover data.
// and the panicHandlerFunc will be called with the job's name and the recover data.
func SetPanicHandler(handler PanicHandlerFunc) {
panicHandlerMutex.Lock()
defer panicHandlerMutex.Unlock()
Expand Down

0 comments on commit 8e88b6b

Please sign in to comment.