我正在嘗試制作一個任務調度程式,它可以在給定的時間間隔內執行任務,并且還可以處理發生的恐慌。我的問題是如何在處理恐慌后繼續執行該功能。
func scheduleTask(task func() error, interval time.Duration, timeout time.Duration) {
//add waitgroup and mutex
var wg sync.WaitGroup
var mtx sync.Mutex
var startTime = time.Now()
//add each task to a goroutine and set interval and timeout to the function
wg.Add(1)
go func() {
defer wg.Done()
for {
//check if the time is up
if time.Since(startTime) > timeout {
break
}
defer func() {
if r := recover(); r != nil {
log.Println("Recovering from panic:", r)
}
}()
mtx.Lock()
task()
mtx.Unlock()
}
}()
wg.Wait()
}
func main() {
var a = 0
scheduleTask(func() error {
time.Sleep(50 * time.Millisecond)
if a == 3 {
a
panic("oops")
}
a
return nil
}, time.Millisecond*100, time.Millisecond*1000)
log.Println(a)
if a != 10 {
log.Fatal("Expected it to be 10")
}
}
uj5u.com熱心網友回復:
恢復時,您將退出當前功能。在這種情況下,您可以輕松地將其包裹task()
在封閉物中。
package main
import (
"log"
"sync"
"time"
)
func scheduleTask(task func() error, interval time.Duration, timeout time.Duration) {
//add waitgroup and mutex
var wg sync.WaitGroup
var mtx sync.Mutex
var startTime = time.Now()
//add each task to a goroutine and set interval and timeout to the function
wg.Add(1)
go func() {
defer wg.Done()
for {
//check if the time is up
if time.Since(startTime) > timeout {
break
}
mtx.Lock()
func() {
defer func() {
if r := recover(); r != nil {
log.Println("Recovering from panic:", r)
}
}()
task()
}()
mtx.Unlock()
}
}()
wg.Wait()
}
func main() {
var a = 0
scheduleTask(func() error {
time.Sleep(50 * time.Millisecond)
if a == 3 {
a
panic("oops")
}
a
return nil
}, time.Millisecond*100, time.Millisecond*1000)
log.Println(a)
if a != 10 {
log.Fatal("Expected it to be 10")
}
}
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473045.html
標籤:去