fix: incorrect download speed

This commit is contained in:
huanghongxun 2020-02-19 21:49:27 +08:00
parent b72d42a09a
commit 1a0be11ae3

View File

@ -21,6 +21,7 @@ import org.jackhuang.hmcl.event.Event;
import org.jackhuang.hmcl.event.EventBus; import org.jackhuang.hmcl.event.EventBus;
import org.jackhuang.hmcl.util.CacheRepository; import org.jackhuang.hmcl.util.CacheRepository;
import org.jackhuang.hmcl.util.Logging; import org.jackhuang.hmcl.util.Logging;
import org.jackhuang.hmcl.util.ToStringBuilder;
import org.jackhuang.hmcl.util.io.*; import org.jackhuang.hmcl.util.io.*;
import java.io.File; import java.io.File;
@ -252,7 +253,6 @@ public class FileDownloadTask extends Task<Void> {
stream = con.getInputStream(); stream = con.getInputStream();
int lastDownloaded = 0, downloaded = 0; int lastDownloaded = 0, downloaded = 0;
long lastTime = System.currentTimeMillis();
byte[] buffer = new byte[IOUtils.DEFAULT_BUFFER_SIZE]; byte[] buffer = new byte[IOUtils.DEFAULT_BUFFER_SIZE];
while (true) { while (true) {
if (isCancelled()) { if (isCancelled()) {
@ -273,14 +273,13 @@ public class FileDownloadTask extends Task<Void> {
// Update progress information per second // Update progress information per second
updateProgress(downloaded, contentLength); updateProgress(downloaded, contentLength);
long now = System.currentTimeMillis();
if (now - lastTime >= 1000) { updateDownloadSpeed(downloaded - lastDownloaded);
updateDownloadSpeed(downloaded - lastDownloaded); lastDownloaded = downloaded;
lastDownloaded = downloaded;
lastTime = now;
}
} }
updateDownloadSpeed(downloaded - lastDownloaded);
closeFiles(); closeFiles();
// Restore temp file to original name. // Restore temp file to original name.
@ -341,7 +340,7 @@ public class FileDownloadTask extends Task<Void> {
timer.schedule(new TimerTask() { timer.schedule(new TimerTask() {
@Override @Override
public void run() { public void run() {
speedEvent.fireEvent(new SpeedEvent(speedEvent, downloadSpeed.getAndSet(0))); speedEvent.channel(SpeedEvent.class).fireEvent(new SpeedEvent(speedEvent, downloadSpeed.getAndSet(0)));
} }
}, 0, 1000); }, 0, 1000);
} }
@ -366,6 +365,11 @@ public class FileDownloadTask extends Task<Void> {
public int getSpeed() { public int getSpeed() {
return speed; return speed;
} }
@Override
public String toString() {
return new ToStringBuilder(this).append("speed", speed).toString();
}
} }
} }