you can use gradle.buildFinished instead check whether the task is last or not
void buildFinished(Closure closure)
Adds a closure to be called when the build is completed. All selected tasks have been executed. A BuildResult instance is passed to the closure as a parameter.
https://docs.gradle.org/3.3/dsl/org.gradle.api.invocation.Gradle.html
you can use gradle.buildFinished instead check whether the task is last or not
https://docs.gradle.org/3.3/dsl/org.gradle.api.invocation.Gradle.html