The code is exposed to the configuration phase, so regenerating the javadoc when it is not needed is slowing down the build process a lot. So I moved it to doLast but the code is never been executed when I call the task. Does type: Javadoc not have a doLast phase?
The doLast {...} block adds the contained code as a task action after the already existing task action. The task never executes either the predefined action to generate the javadoc or your custom action due to up-to-date checking. All of the code in the doLast {...} above is configuration code that should execute in the configuration phase, but the javadoc is not actually generated until the execution phase.
If you are seeing javadoc always generated, I believe you might have an unintetional dependency on the task or other code outside of what you have shared that is causing this.