Skip to content

Instantly share code, notes, and snippets.

@RobinCheptileh
Created July 22, 2018 13:49
Show Gist options
  • Save RobinCheptileh/7136a4077bb182fcd85e8d990ca4da19 to your computer and use it in GitHub Desktop.
Save RobinCheptileh/7136a4077bb182fcd85e8d990ca4da19 to your computer and use it in GitHub Desktop.
A simple java class demonstrating how to use a Java Timer
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
// Instantiate new timer
Timer timer = new Timer(true);
System.out.println("Timer started!");
// Schedule a timer for every second
// Declare anonymous TimerTask
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("Timer!");
}
}, 0, 1000);
// Sleep thread for 20 seconds
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Cancel timer after 20 seconds
timer.cancel();
System.out.println("Timer stopped!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment