Created
July 22, 2018 13:49
-
-
Save RobinCheptileh/7136a4077bb182fcd85e8d990ca4da19 to your computer and use it in GitHub Desktop.
A simple java class demonstrating how to use a Java Timer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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