Executing gradle task as apart of a projects build

I have a master project setup that manages multiple gradle projects that each have their own build.gradle file. I have one task that I need to have executed as apart of a managed projects build (this task generates java files to the main src of that project)

What is the correct way of specifying in that dependent projects build.gradle file that it has a dependency on a task. So far I could only come up with this:

tasks.build.dependsOn(rootProject.tasks.myTaskToGenerate)

That line in the root project build.gradle wrapped in a subprojects block seems like it should work, e.g.,

subprojects {
tasks.build.dependsOn(rootProject.tasks.myTaskToGenerate)
}