Reusable Scripts with the Execute Script Scheduled Task

Continuing the discussion from Advanced Use Cases for the Nexus Repository Manager API:

One of the lesser known scheduled tasks in Nexus Repository Manager 3 is the “Execute Script”. This utilizes the same API as the groovy based Integrations API. The benefit of the task is that it can be scheduled to run automatically. Because it runs autonomously, the downside of running a script with the scheduled task is that there is no input or output other than logging to the nexus.log file.

This means that if you want to run the same groovy code with different options, say perform custom cleanup on multiple hosted repositories, you will need to cut and paste the code. This was recently asked on our nexus-users@sonatype.com mailing list, https://groups.google.com/a/glists.sonatype.com/d/topic/nexus-users/fDjbCjfiPM4/discussion.

Rather than cut-and-paste the script into several scheduled tasks, it would be nice to save the script once and then call it from each scheduled task with the appropriate parameters. Kelly Robinson came up with this solution (where ‘test’ is the same of a groovy script added using the Integrations API):

import org.sonatype.nexus.script.ScriptManager
import org.sonatype.nexus.common.script.ScriptService

def scriptManager = container.lookup(ScriptManager.name)
def scriptService = container.lookup(ScriptService.name)
def script = scriptManager.get('test')
Object result = scriptService.eval(script.type, script.content, [log:log])