Skip to content

Instantly share code, notes, and snippets.

@RobinCheptileh
Created July 22, 2018 13:49
Show Gist options
  • Select an option

  • Save RobinCheptileh/7136a4077bb182fcd85e8d990ca4da19 to your computer and use it in GitHub Desktop.

Select an option

Save RobinCheptileh/7136a4077bb182fcd85e8d990ca4da19 to your computer and use it in GitHub Desktop.

Revisions

  1. RobinCheptileh created this gist Jul 22, 2018.
    30 changes: 30 additions & 0 deletions TimerTask.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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!");
    }
    }