github.com/fzfile/BaiduPCS-Go@v0.0.0-20200606205115-4408961cf336/requester/uploader/status.go (about) 1 package uploader 2 3 import ( 4 "time" 5 ) 6 7 type ( 8 // Status 上传状态接口 9 Status interface { 10 TotalSize() int64 // 总大小 11 Uploaded() int64 // 已上传数据 12 SpeedsPerSecond() int64 // 每秒的上传速度 13 TimeElapsed() time.Duration // 上传时间 14 } 15 16 // UploadStatus 上传状态 17 UploadStatus struct { 18 totalSize int64 // 总大小 19 uploaded int64 // 已上传数据 20 speedsPerSecond int64 // 每秒的上传速度 21 timeElapsed time.Duration // 上传时间 22 } 23 24 UploadStatusFunc func(status Status, updateChan <-chan struct{}) 25 ) 26 27 // TotalSize 返回总大小 28 func (us *UploadStatus) TotalSize() int64 { 29 return us.totalSize 30 } 31 32 // Uploaded 返回已上传数据 33 func (us *UploadStatus) Uploaded() int64 { 34 return us.uploaded 35 } 36 37 // SpeedsPerSecond 返回每秒的上传速度 38 func (us *UploadStatus) SpeedsPerSecond() int64 { 39 return us.speedsPerSecond 40 } 41 42 // TimeElapsed 返回上传时间 43 func (us *UploadStatus) TimeElapsed() time.Duration { 44 return us.timeElapsed 45 } 46 47 // GetStatusChan 获取上传状态 48 func (u *Uploader) GetStatusChan() <-chan Status { 49 c := make(chan Status) 50 51 go func() { 52 for { 53 select { 54 case <-u.finished: 55 close(c) 56 return 57 default: 58 if !u.executed { 59 time.Sleep(1 * time.Second) 60 continue 61 } 62 63 old := u.readed64.Readed() 64 time.Sleep(1 * time.Second) // 每秒统计 65 66 readed := u.readed64.Readed() 67 c <- &UploadStatus{ 68 totalSize: u.readed64.Len(), 69 uploaded: readed, 70 speedsPerSecond: readed - old, 71 timeElapsed: time.Since(u.executeTime) / 1e7 * 1e7, 72 } 73 } 74 } 75 }() 76 return c 77 } 78 79 func (muer *MultiUploader) uploadStatusEvent() { 80 if muer.onUploadStatusEvent == nil { 81 return 82 } 83 84 go func() { 85 ticker := time.NewTicker(1 * time.Second) // 每秒统计 86 defer ticker.Stop() 87 for { 88 select { 89 case <-muer.finished: 90 return 91 case <-ticker.C: 92 readed := muer.workers.Readed() 93 muer.onUploadStatusEvent(&UploadStatus{ 94 totalSize: muer.file.Len(), 95 uploaded: readed, 96 speedsPerSecond: muer.speedsStat.GetSpeeds(), 97 timeElapsed: time.Since(muer.executeTime) / 1e8 * 1e8, 98 }, muer.updateInstanceStateChan) 99 } 100 } 101 }() 102 }