0

I have the following Timer code below, but want to write is a lambda expression.

    private void setupPollingTimmer() {
        timer.scheduleAtFixedRate(new DownloadMessagesAndDisplayTask(), TIMERPERIOD,TIMERPERIOD);
    }

    private class DownloadMessagesAndDisplayTask extends TimerTask {
        public void run() {
            DownloadMessagesAndDisplay();
//            timer.cancel(); //Not necessary because we call System.exit
        }
    }

I have looked around google and even tried () -> but it doesnt like it.

Also If there is a better version of Timer I should be using please say so.

NOTE: the supposed duplicate is not a duplicate, as its ticked answer doesn't use lambda expression. I have ticked the correct answer below.

f1wade
  • 2,877
  • 6
  • 27
  • 43
  • 1
    When you say 'it doesn't like it', what doesn't like it? Could you post the code that is failing. – mikea May 09 '16 at 14:36

1 Answers1

1

Unfortunately, java 8 designers decided to not support SAM abstract classes, only interfaces. As TimerTask is abstract class, you cannot use lambda directly with it.

You can possibly implement your own variation of it (MyTask), accepting Runnable as parameter, implementing run() method to call run on passed Runnable and then scheduling new MyTask(()-> DownloadMessagesAndDisplay());

Alternatively, consider one of java dialects (groovy, xtend, koitlin) which will allow using closures/lambdas syntax with SAM abstract classes.

Artur Biesiadowski
  • 3,595
  • 2
  • 13
  • 18