processtmp.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "time"
  6. "github.com/fatih/color"
  7. "github.com/vbauerster/mpb/v8"
  8. "github.com/vbauerster/mpb/v8/decor"
  9. )
  10. func process() {
  11. // to support color in Windows following both options are required
  12. p := mpb.New(
  13. mpb.WithOutput(color.Output),
  14. mpb.WithAutoRefresh(),
  15. )
  16. red, green := color.New(color.FgRed), color.New(color.FgGreen)
  17. fmt.Println("应用更新中...")
  18. task := "windows.zip"
  19. queue := make([]*mpb.Bar, 2)
  20. queue[0] = p.AddBar(rand.Int63n(201)+100,
  21. mpb.PrependDecorators(
  22. decor.Name(task, decor.WC{C: decor.DindentRight | decor.DextraSpace}),
  23. decor.Name("下载中:", decor.WCSyncSpaceR),
  24. decor.CountersNoUnit("%d / %d", decor.WCSyncWidth),
  25. ),
  26. mpb.AppendDecorators(
  27. decor.OnComplete(decor.Percentage(decor.WC{W: 5}), "done"),
  28. ),
  29. )
  30. queue[1] = p.AddBar(rand.Int63n(101)+100,
  31. mpb.BarQueueAfter(queue[0]), // this bar is queued
  32. mpb.BarFillerClearOnComplete(),
  33. mpb.PrependDecorators(
  34. decor.Name(task, decor.WC{C: decor.DindentRight | decor.DextraSpace}),
  35. decor.OnCompleteMeta(
  36. decor.OnComplete(
  37. decor.Meta(decor.Name("安装中:", decor.WCSyncSpaceR), toMetaFunc(red)),
  38. "更新完成!",
  39. ),
  40. toMetaFunc(green),
  41. ),
  42. decor.OnComplete(decor.EwmaETA(decor.ET_STYLE_MMSS, 0, decor.WCSyncWidth), ""),
  43. ),
  44. mpb.AppendDecorators(
  45. decor.OnComplete(decor.Percentage(decor.WC{W: 5}), ""),
  46. ),
  47. )
  48. go func() {
  49. for _, b := range queue {
  50. complete(b)
  51. }
  52. }()
  53. p.Wait()
  54. }
  55. func complete(bar *mpb.Bar) {
  56. max := 100 * time.Millisecond
  57. for !bar.Completed() {
  58. // start variable is solely for EWMA calculation
  59. // EWMA's unit of measure is an iteration's duration
  60. start := time.Now()
  61. time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10)
  62. // we need to call EwmaIncrement to fulfill ewma decorator's contract
  63. bar.EwmaIncrInt64(rand.Int63n(5)+1, time.Since(start))
  64. }
  65. }
  66. func toMetaFunc(c *color.Color) func(string) string {
  67. return func(s string) string {
  68. return c.Sprint(s)
  69. }
  70. }