github.com/timandy/routine@v1.1.4-0.20240507073150-e4a3e1fe2ba5/api_future_task.go (about) 1 package routine 2 3 import "time" 4 5 // FutureCallable provides a future function that returns a value of type TResult. 6 type FutureCallable[TResult any] func(task FutureTask[TResult]) TResult 7 8 // CancelToken propagates notification that operations should be canceled. 9 type CancelToken interface { 10 // IsCanceled returns true if task was canceled. 11 IsCanceled() bool 12 13 // Cancel notifies the waiting coroutine that the task has canceled and returns stack information. 14 Cancel() 15 } 16 17 // FutureTask provide a way to wait for the sub-coroutine to finish executing, get the return value of the sub-coroutine, and catch the sub-coroutine panic. 18 type FutureTask[TResult any] interface { 19 // IsDone returns true if completed in any fashion: normally, exceptionally or via cancellation. 20 IsDone() bool 21 22 // IsCanceled returns true if task was canceled. 23 IsCanceled() bool 24 25 // IsFailed returns true if completed exceptionally. 26 IsFailed() bool 27 28 // Complete notifies the waiting coroutine that the task has completed normally and returns the execution result. 29 Complete(result TResult) 30 31 // Cancel notifies the waiting coroutine that the task has canceled and returns stack information. 32 Cancel() 33 34 // Fail notifies the waiting coroutine that the task has terminated due to panic and returns stack information. 35 Fail(error any) 36 37 // Get return the execution result of the sub-coroutine, if there is no result, return nil. 38 // If task is canceled, a panic with cancellation will be raised. 39 // If panic is raised during the execution of the sub-coroutine, it will be raised again at this time. 40 Get() TResult 41 42 // GetWithTimeout return the execution result of the sub-coroutine, if there is no result, return nil. 43 // If task is canceled, a panic with cancellation will be raised. 44 // If panic is raised during the execution of the sub-coroutine, it will be raised again at this time. 45 // If the deadline is reached, a panic with timeout error will be raised. 46 GetWithTimeout(timeout time.Duration) TResult 47 48 // Run execute the task, the method can be called repeatedly, but the task will only execute once. 49 Run() 50 } 51 52 // NewFutureTask Create a new instance. 53 func NewFutureTask[TResult any](callable FutureCallable[TResult]) FutureTask[TResult] { 54 if callable == nil { 55 panic("callable can not be nil.") 56 } 57 task := &futureTask[TResult]{callable: callable} 58 task.await.Add(1) 59 return task 60 }