I am trying to create a code that calls the system time and updates it every minute. Can anybody give me an example that will steer me in the right direction? thanks
Asked
Active
Viewed 2,204 times
3
-
1Date now = new Date() will get the system time :) – willcodejavaforfood Sep 13 '10 at 17:21
-
2Updates the system time, or an internal timer to the software? – aperkins Sep 13 '10 at 17:30
-
2The OS takes care of this? I don't think you should screw with the system time like that. – Alfred Sep 13 '10 at 18:04
-
Later duplicate: [Java timer to make a function run every minute](http://stackoverflow.com/q/23445137/642706) and [Running a Java Thread in intervals](http://stackoverflow.com/q/426758/642706) – Basil Bourque Aug 15 '16 at 03:19
2 Answers
5
I think that you're looking for a Timer
. It can schedule a task such as updating anything every minute.
public class MyScheduledTask extends TimerTask{
public void run(){
System.out.println("Message printed every minute");
}
}
public class Main{
public static void main(String... args){
Timer timer = new Timer();
timer.schedule(new MyScheduledTask(), 0, 60*1000);
//Do something that takes time
}
}
For the current system time you can use System.currentTimeMillis()
.
Resources :

Colin Hebert
- 91,525
- 15
- 160
- 151
-
i see that i would need a timer but wouldn't i need a counter also in order for the time to update every minute – Rafiq Flucas Sep 13 '10 at 19:59
-
The timer.schedule count itself, the `60*1000` argument says it will call the `run()` method of `MyScheduledTask` every 60*1000 milliseconds. – Colin Hebert Sep 13 '10 at 20:02
-
import java.util.Timer; import java.util.TimerTask; public class CAARSCounter_1 extends TimerTask{ public void run(){ System.out.println("Message printed every minute");} public static void currentTimeMillis(){ } public void main(String... args){ Timer timer = new Timer(); timer.schedule(new CAARSCounter_1(),0 , 60*1000);} } – Rafiq Flucas Sep 13 '10 at 20:07
-
You don't have to define your own `currentTimeMillis()`. But it's about right. – Colin Hebert Sep 13 '10 at 20:16
-
Edit your question and put this code in it, and mark it as code so it doesn't wrap like this. – Stephen P Sep 13 '10 at 20:17
-
I seem to have a plethora of questions lol but, how would i get the time to print to the screen every minute – Rafiq Flucas Sep 13 '10 at 20:26
-
You can use either `Date now = new Date()` as suggested in comments and print it or `currentTimeMillis()` to get the currentTime as a long. – Colin Hebert Sep 14 '10 at 20:27
1
If you were just looking to create a timer you could create a Thread to execute every second within an infinite loop
public class SystemTime extends Thread {
@Override
public void run(){
while (true){
String time = new SimpleDateFormat("HH:MM:ss").format(Calendar.getInstance().getTime());
System.out.println(time);
try{
Thread.sleep(1000);
} catch (InterruptedException ie){
return;
}
}
}
}

Squeeky91
- 11
- 2