Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "time"
  6. )
  7.  
  8. const total = 5 * time.Second
  9.  
  10. type process struct {
  11. step time.Duration
  12. total time.Duration
  13. }
  14.  
  15. type processes map[int]*process
  16.  
  17. func main() {
  18. var currentProcesses = make(processes)
  19. var progressBar = make(chan int, len(currentProcesses))
  20.  
  21. currentProcesses.AddProcess(1, total)
  22. currentProcesses.AddProcess(2, total)
  23. currentProcesses.AddProcess(3, total)
  24.  
  25. go writeOutput(progressBar, currentProcesses)
  26.  
  27. progressBar <- 1
  28. progressBar <- 2
  29. progressBar <- 3
  30.  
  31. go updateProgressBar(progressBar, currentProcesses, 1, 1000*time.Millisecond)
  32. go updateProgressBar(progressBar, currentProcesses, 2, 500*time.Millisecond)
  33. go updateProgressBar(progressBar, currentProcesses, 3, 100*time.Millisecond)
  34.  
  35. time.Sleep(10 * time.Second)
  36. }
  37.  
  38. func (p processes) AddProcess(id int, total time.Duration) {
  39. p[id] = &process{total: total}
  40. }
  41.  
  42. func (p *process) UpdateProcess(step time.Duration) {
  43. p.step = step
  44. }
  45.  
  46. func updateProgressBar(progressBar chan<- int, currentProcesses processes, id int, step time.Duration) {
  47. steps := int(currentProcesses[id].total) / int(step)
  48.  
  49. for i := 0; i < steps; i++ {
  50. time.Sleep(step)
  51. currentProcesses[id].UpdateProcess(time.Duration((i+1) * int(step)))
  52. progressBar <- id
  53. }
  54. }
  55.  
  56. func writeOutput(progressBar <-chan int, currentProcesses processes) {
  57. for {
  58. x := <-progressBar
  59. s := ""
  60. for _, process := range currentProcesses {
  61. s += outputProgress(x, int(process.step), int(process.total))
  62. }
  63.  
  64. fmt.Printf("\033[0;0H")
  65. fmt.Print(s)
  66. }
  67. }
  68.  
  69. func outputProgress(id int, step, total int) string {
  70. current := percent(step, total)
  71. s := fmt.Sprintf("Doing Task %d [", id)
  72.  
  73. for i := 0; i < current; i++ {
  74. s += "="
  75. }
  76.  
  77. for i := current; i < 100; i++ {
  78. s += " "
  79. }
  80.  
  81. s += fmt.Sprintf("] %d%%\r\n", current)
  82.  
  83. return s
  84. }
  85.  
  86. func percent(step, total int) int {
  87. return int(float32(step) / float32(total) * 100)
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement