Advertisement
obernardovieira

Schedule a task!

Dec 15th, 2016
379
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. /*
  2.  * This is only a simple example of schedules
  3.  */
  4. package beeper;
  5.  
  6. import java.util.concurrent.Executors;
  7. import java.util.concurrent.ScheduledExecutorService;
  8. import java.util.concurrent.ScheduledFuture;
  9. import static java.util.concurrent.TimeUnit.SECONDS;
  10.  
  11. /**
  12.  *
  13.  * @author bernardovieira
  14.  */
  15. public class Beeper {
  16.    
  17.     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  18.     /**
  19.      * @param args the command line arguments
  20.      */
  21.     public static void main(String[] args) {
  22.         // TODO code application logic here
  23.        
  24.        
  25.        
  26.         Beeper beep = new Beeper();
  27.         beep.beepForAnHour();
  28.         beep.stopIt();
  29.    
  30.    
  31.     }
  32.    
  33.     public void stopIt()
  34.     {
  35.         new Thread(new Runnable() {
  36.             @Override
  37.             public void run() {
  38.                
  39.                 try {
  40.                     Thread.sleep(2000);
  41.                     scheduler.shutdown();
  42.                 } catch (InterruptedException ex) { }
  43.                
  44.                 //if you want to start another beeper
  45.                 //just uncomment the code below
  46.  
  47.                 /*Beeper beep = new Beeper();
  48.                 beep.beepForAnHour();
  49.                 beep.stopIt();*/
  50.             }
  51.         }).start();
  52.     }
  53.    
  54.     public void beepForAnHour()
  55.     {
  56.         final Runnable beeper = new Runnable()
  57.         {
  58.             @Override
  59.             public void run()
  60.             {
  61.                 System.out.println("beep");
  62.             }
  63.         };
  64.         scheduler.scheduleAtFixedRate(beeper, 1, 1, SECONDS);
  65.     }
  66.    
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement