github.com/qjfoidnh/BaiduPCS-Go@v0.0.0-20231011165705-caa18a3765f3/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 80 // 使用中的速度状态 81 func (muer *MultiUploader) uploadStatusEvent() { 82 if muer.onUploadStatusEvent == nil { 83 return 84 } 85 86 go func() { 87 ticker := time.NewTicker(3 * time.Second) // 每3秒统计 88 //ticker := time.NewTicker(990 * time.Millisecond) // 每秒统计 89 defer ticker.Stop() 90 for { 91 select { 92 case <-muer.finished: 93 return 94 case <-ticker.C: 95 readed := muer.workers.Readed() 96 muer.onUploadStatusEvent(&UploadStatus{ 97 totalSize: muer.file.Len(), 98 uploaded: readed, 99 speedsPerSecond: muer.speedsStat.GetSpeeds(), 100 timeElapsed: time.Since(muer.executeTime) / 1e8 * 1e8, 101 }, muer.updateInstanceStateChan) 102 } 103 } 104 }() 105 }