When you use
someTask {
someMethod()
}
then it means to gradle that it must call someMethod()
when configuring the task, in the first phase that parses the build script and decides which tasks exist and what depends on what.
To define what must happen when the task is executed, in the second phase, you must use the following syntax:
someTask << {
someMethod()
}