Question

I am working on a download timer programmed in Java. My goal is to automatically start the timer when the download begins and stop it as it stops. I have a basic timer that counts seconds as the program starts, but I am having problems automating it. I have researched java.io, but I'm not sure if this is what I need.

This is my code so far:

package sciencePackage;

public class Timer extends Thread {
    @Override
    public void run() {
        super.run();
        try {

            for (int i = 1;i < 61; i++)  {

                this.sleep(1000);
                System.out.println("System is still running -- " + i );
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}

No correct solution

OTHER TIPS

Creating a Timer class seems excessive for the use that you propose, not to mention that there is already a Timer class built into Java. However, timers are best used for scheduling actions, not for observing how long they take.

Also, in the code you posted, you have super.run() finish before you even start timing. At that point, there is nothing left for your timer to wait for, unless your download is happening on a different thread that you haven't told us about.

Instead, you could probably do something much simpler, like this:

public void run() {
    long startTime = System.nanoTime();
    super.run(); 
    long endTime = System.nanoTime();
    System.out.println("Download Time: " + (end - start) / 1.0e9 + " seconds");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top