Creating Dynamic Tasks On Demand

I’m working on a gradle script which downloads various plugins for my IDE (Jetbrains MPS).
The plugins I want to install are in a list called mpsPlugins.
However, each plugin can also depend on other plugins which might depend on other plugins and so on.
This dependency can be looked up using a few HTTP requests.

The current version of the script has a task downloadMpsPlugins which delegates the actual work to a private method, which first looks up all dependencies and transitive dependencies and adds them to the mpsPlugins list. Then it iterates over the list and downloads each plugin.

I now want to introduce caching for each downloaded file and therefore need to change it from a loop inside a method to a set of dynamically created tasks (on for each file to be downloaded).

However, I cannot create these tasks everytime the gradle script is loaded, as the dependency resolution is costly (takes time and I don’t want to spam their servers).
Therefore, I’d like to create these dynamic tasks only when I know that the task downloadMpsPlugins will run.

Is this possible somehow?

For anyone wanting to look at the actual scripts, the current version is here: