How to use TimerTask with lambdas?

后端 未结 5 1611
逝去的感伤
逝去的感伤 2020-12-05 14:29

As you hopefully know you can use lambdas in Java 8, for example to replace anonymous methods.

An example can be seen here of Java 7 vs Java 8:

Runna         


        
相关标签:
5条回答
  • 2020-12-05 14:44

    To complete Marko Topolnik's answer about Timer, you just have to call schedule method with a lambda.

    schedule(() -> {
        System.out.println("Task #1 is running");
    }, 500);
    
    0 讨论(0)
  • 2020-12-05 14:51

    Noting first that Timer is effectively an antiquated API, but entertaining your question nevertheless, you could write a small wrapper around it which would adapt the schedule method to accept a Runnable, and on the inside you'd turn that Runnable into a TimerTask. Then you would have your schedule method which would accept a lambda.

    public class MyTimer {
      private final Timer t = new Timer();
    
      public TimerTask schedule(final Runnable r, long delay) {
         final TimerTask task = new TimerTask() { public void run() { r.run(); }};
         t.schedule(task, delay);
         return task;
      }
    }
    
    0 讨论(0)
  • 2020-12-05 14:55

    While Marko's answer is perfectly correct, I prefer my implementation:

    public class FunctionalTimerTask extends TimerTask {
    
        Runnable task;
    
        public FunctionalTimerTask(Runnable task) {
            this.task = task;
        }
    
        @Override
        public void run() {
            task.run();
        }
    }
    
     public static class Task {
        public static TimerTask set(Runnable run) {
            return new FunctionalTimerTask(() -> System.err.println("task"));
        }
    }
    
     Timer timer = new Timer(false);
     timer.schedule(Task.set(() -> doStuff()), TimeUnit.SECONDS.toMillis(1));
    

    This gives you more control over the timer, and you have a static utility class. Idealy give it a name that won't conflict with other common thread class, so not Task, Job, Timer.

    0 讨论(0)
  • 2020-12-05 14:58

    I know this is an old post, but for completeness, I wanted to include the wrapper solution posted by Flown:

    private static TimerTask wrap(Runnable r) {
      return new TimerTask() {
    
        @Override
        public void run() {
          r.run();
        }
      };
    }
    

    then your call can become:

    timer.schedule(wrap(this::checkDirectory), delay);
    
    0 讨论(0)
  • 2020-12-05 15:02

    You can also create a Timer easily with lambdas from the Swing API if you want (but not with TimerTask) :

    new javax.swing.Timer(1000, (ae) -> this::checkDirectory).start();

    0 讨论(0)
提交回复
热议问题