基本示例

  1. 2021-05-27 13:28:19 1.004516s
  2. 2021-05-27 13:28:20 997.262ms
  3. 2021-05-27 13:28:21 999.972ms
  4. 2021-05-27 13:28:22 1.00112s
  5. 2021-05-27 13:28:23 998.773ms
  6. 2021-05-27 13:28:24 999.957ms
  7. 2021-05-27 13:28:25 1.002468s
  8. 2021-05-27 13:28:26 997.468ms
  9. 2021-05-27 13:28:27 999.981ms
  10. 2021-05-27 13:28:28 1.002504s

单例任务

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/os/gctx"
  5. "github.com/gogf/gf/v2/os/glog"
  6. "github.com/gogf/gf/v2/os/gtimer"
  7. "time"
  8. )
  9. func main() {
  10. var (
  11. ctx = gctx.New()
  12. interval = time.Second
  13. )
  14. gtimer.AddSingleton(ctx, interval, func(ctx context.Context) {
  15. glog.Print(ctx, "doing")
  16. time.Sleep(5 * time.Second)
  17. })
  18. }

执行后,输出结果为:

延迟任务

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. "github.com/gogf/gf/v2/os/gtime"
  7. "github.com/gogf/gf/v2/os/gtimer"
  8. "time"
  9. )
  10. func main() {
  11. var (
  12. ctx = gctx.New()
  13. delay = time.Second
  14. interval = time.Second
  15. )
  16. fmt.Println("Start:", gtime.Now())
  17. gtimer.DelayAdd(
  18. ctx,
  19. delay,
  20. interval,
  21. func(ctx context.Context) {
  22. fmt.Println("Running:", gtime.Now())
  23. },
  24. )
  25. select {}
  26. }

执行后,终端输出:

  1. Start: 2021-05-27 13:26:02
  2. Running: 2021-05-27 13:26:04
  3. Running: 2021-05-27 13:26:05
  4. Running: 2021-05-27 13:26:06
  5. Running: 2021-05-27 13:26:07
  6. Running: 2021-05-27 13:26:08
  7. Running: 2021-05-27 13:26:10
  8. Running: 2021-05-27 13:26:11
  9. ...

SetTimeout

执行后,终端输出:

  1. SetInterval: 2021-05-27 13:20:50
  2. SetTimeout: 2021-05-27 13:20:50
  3. SetInterval: 2021-05-27 13:20:51
  4. SetInterval: 2021-05-27 13:20:52
  5. SetInterval: 2021-05-27 13:20:53
  6. SetInterval: 2021-05-27 13:20:54
  7. SetInterval: 2021-05-27 13:20:55
  8. SetInterval: 2021-05-27 13:20:56
  9. SetInterval: 2021-05-27 13:20:57
  10. SetInterval: 2021-05-27 13:20:58
  11. ...

Exit退出

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. "github.com/gogf/gf/v2/os/gtime"
  7. "github.com/gogf/gf/v2/os/gtimer"
  8. "time"
  9. )
  10. func main() {
  11. var (
  12. ctx = gctx.New()
  13. )
  14. gtimer.SetInterval(ctx, time.Second, func(ctx context.Context) {
  15. fmt.Println("exit:", gtime.Now())
  16. gtimer.Exit()
  17. })
  18. select {}

执行后,终端输出: