Automate Tasks with Groovy Scripts

by Didin J. on Jul 17, 2025 Automate Tasks with Groovy Scripts

Learn how to automate repetitive tasks using Groovy scripts. Boost productivity with powerful scripting techniques for files, databases, APIs, and more.

Automation is a powerful way to increase productivity, reduce manual effort, and eliminate human error. Whether you're a developer, DevOps engineer, or system administrator, scripting repetitive tasks can save hours of work. While there are many scripting languages available, Groovy offers a unique blend of power and simplicity, especially for those already working within the Java ecosystem.

Groovy is a dynamic language for the JVM that builds upon Java syntax but with a much more concise and expressive style. It’s widely used in Gradle build scripts, Jenkins pipelines, and custom automation tools, making it a perfect choice for writing scripts to automate everyday tasks.

In this tutorial, we’ll walk through how to:

  • Write and run standalone Groovy scripts

  • Automate file operations like renaming and moving files

  • Run system or shell commands directly from Groovy

  • Schedule recurring tasks using your OS's built-in scheduler

  • Leverage Groovy in build systems like Gradle or CI tools like Jenkins

By the end, you’ll have the skills to build flexible, reusable Groovy scripts for automating your development workflow, server tasks, or CI/CD processes.

Let’s begin by setting up the environment.


1. Prerequisites

Before diving into Groovy scripting, make sure you have the following tools installed:

Java (JDK 8 or higher)

Groovy runs on the Java Virtual Machine (JVM), so a Java Development Kit (JDK) is required.

To check if Java is installed:

java -version

If not installed, download it from https://adoptium.net or use a package manager:

# macOS
brew install openjdk

# Ubuntu/Debian
sudo apt install openjdk-17-jdk

Groovy

Install Groovy using SDKMAN (recommended):

curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
sdk install groovy

To verify:

groovy -version

Alternatively, you can download binaries from https://groovy-lang.org/download.html


2. Writing Your First Groovy Script

Let’s create a simple script that prints a welcome message.

Create a file called hello.groovy:

// hello.groovy
def name = "Djamware"
println "Hello, $name! Groovy is ready to automate your tasks."

Run it with:

groovy hello.groovy

Output:

Hello, Djamware! Groovy is ready to automate your tasks.

Groovy uses dynamic typing, string interpolation, and concise syntax, making it ideal for scripting without boilerplate.


3. Automate File Operations with Groovy

Groovy simplifies file operations compared to Java. You can easily read, write, copy, move, or delete files with minimal code.

✅ Reading a File

Create a file named sample.txt with the following content:

Groovy is powerful.
Groovy is concise.
Groovy is fun!

Now, use this Groovy script to read and print the file content:

// read-file.groovy
def file = new File('sample.txt')
file.eachLine { line ->
    println line
}

Run it:

groovy read-file.groovy

Automate Tasks with Groovy Scripts - read file

Writing to a File

Let’s create or overwrite a file with some content:

// write-file.groovy
def file = new File('output.txt')
file.text = 'Automated file writing with Groovy!\nLine 2 added.'

To append instead of overwrite:

file << '\nAppending another line.'

Automate Tasks with Groovy Scripts - write file

✅ Copying a File

// copy-file.groovy
def source = new File('sample.txt')
def target = new File('copied.txt')
target.text = source.text

✅ Deleting a File

// delete-file.groovy
def file = new File('copied.txt')
if (file.exists()) {
    file.delete()
    println "File deleted successfully."
} else {
    println "File not found."
}

These simple file operations can be used to automate tasks like:

  • Generating reports

  • Archiving logs

  • Cleaning up directories

  • Processing CSV or config files


4. Executing Shell/System Commands in Groovy Scripts

Groovy provides a very convenient way to execute system-level or shell commands using the execute() method available on String objects. This allows you to automate tasks such as:

  • Running terminal commands

  • Starting other applications

  • Managing system services

✅ Run a Basic Shell Command

// run-command.groovy
def command = 'ls -la' // On Windows, use 'dir'
def process = command.execute()
process.in.eachLine { line ->
    println line
}

Tip: Always use platform-appropriate commands (ls for Unix/macOS/Linux, dir for Windows).

✅ Capture Output and Errors

def process = 'git --version'.execute()
def output = process.text
println "Git Version:\n$output"

To capture error output:

def badCmd = 'some-nonexistent-command'.execute()
badCmd.waitFor()
println "Exit code: ${badCmd.exitValue()}"
println "Error: ${badCmd.err.text}"

✅ Pass Arguments and Environment Variables

def env = ["MY_ENV_VAR=Groovy"]
def cmd = ['bash', '-c', 'echo $MY_ENV_VAR']
def proc = cmd.execute(env, null)
println proc.text.trim()

✅ Execute and Wait for Completion

def p = 'sleep 2'.execute() // Waits 2 seconds
p.waitFor()
println "Done sleeping."

This technique is powerful when automating:

  • Deployment pipelines

  • Backup or cleanup routines

  • Invoking other scripts/tools

  • CI/CD processes


5. Scheduling Tasks with Timer and cron in Groovy

Automating tasks often means scheduling them to run periodically — daily, hourly, or at fixed intervals. In Groovy, this can be done using:

  • The built-in Timer and TimerTask classes

  • External tools like cron (Unix-based systems)

  • Job schedulers (e.g., Quartz)

Let’s start with Groovy's built-in scheduling.

✅ Using Timer and TimerTask

This is great for simple in-script scheduling.

// timer-schedule.groovy
def timer = new Timer()
timer.scheduleAtFixedRate({
    println "Task running at: ${new Date()}"
} as TimerTask, 0, 5000) // run immediately, then every 5 seconds

// Keep the script alive for 20 seconds
sleep(20000)
timer.cancel()

This will print the message every 5 seconds, for 20 seconds total.

✅ Schedule a Delayed One-Time Task

def timer = new Timer()
timer.schedule({
    println "Delayed task executed at ${new Date()}"
} as TimerTask, 3000) // run after 3 seconds

sleep(5000)
timer.cancel()

✅ Using cron to Run Groovy Scripts Periodically (Linux/macOS)

You can use cron to schedule a Groovy script to run on a schedule (like daily at midnight).

1. Make sure your script is executable: 

chmod +x /path/to/your-script.groovy

2. Open your crontab:

crontab -e

3. Add an entry:

0 0 * * * groovy /path/to/your-script.groovy >> /var/log/groovy-task.log 2>&1

This runs the script every day at 00:00 and logs the output.

✅ Bonus: Use Quartz Scheduler (Optional)

For complex jobs with retry logic, time zones, persistence, etc., you can use the Quartz library in Groovy scripts or applications. Let me know if you want an example using Quartz.


6. Real-World Groovy Automation Examples

Now that we’ve covered the basics, let’s dive into practical examples where Groovy scripting can shine in automating daily tasks.

📁 Example 1: Automatically Backing Up Files

A script that copies a directory’s contents into a timestamped backup folder.

// backup.groovy
def sourceDir = new File("/path/to/source")
def backupDir = new File("/path/to/backup/${new Date().format('yyyyMMdd_HHmmss')}")

if (!backupDir.exists()) {
    backupDir.mkdirs()
}

sourceDir.eachFile { file ->
    def destFile = new File(backupDir, file.name)
    file.withInputStream { is ->
        destFile.withOutputStream { os ->
            os << is
        }
    }
}

println "Backup completed to: ${backupDir.absolutePath}"

📝 Run with cron to automate nightly backups.

🧹 Example 2: Clean Up Old Log Files

Delete .log files older than 7 days.

// cleanup-logs.groovy
def logsDir = new File("/var/log/myapp")
def now = System.currentTimeMillis()

logsDir.eachFileMatch(~/.*\.log/) { file ->
    def ageInDays = (now - file.lastModified()) / (1000 * 60 * 60 * 24)
    if (ageInDays > 7) {
        println "Deleting old log: ${file.name}"
        file.delete()
    }
}

This is perfect for keeping your servers clean and efficient.

📤 Example 3: Send Email Reports Automatically

You can send emails from a Groovy script using the javax.mail package.

@Grab('com.sun.mail:javax.mail:1.6.2')
import javax.mail.*
import javax.mail.internet.*

def sendEmail(subject, content) {
    def props = new Properties()
    props.put("mail.smtp.host", "smtp.example.com")
    props.put("mail.smtp.port", "587")
    props.put("mail.smtp.auth", "true")
    props.put("mail.smtp.starttls.enable", "true")

    def session = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("[email protected]", "your_password")
        }
    })

    def message = new MimeMessage(session)
    message.setFrom(new InternetAddress("[email protected]"))
    message.setRecipients(Message.RecipientType.TO, "[email protected]")
    message.setSubject(subject)
    message.setText(content)

    Transport.send(message)
    println "Email sent!"
}

sendEmail("Daily Report", "This is your daily report content.")

🛡️ Be cautious: Store credentials in environment variables or config files, not in code.

📊 Example 4: Generate CSV Report from JSON API

Fetch JSON data from an API and convert it to a CSV file.

@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7.2')
import groovyx.net.http.RESTClient
import groovy.json.JsonSlurper

def client = new RESTClient('https://jsonplaceholder.typicode.com/')
def response = client.get(path: 'users')

def users = new JsonSlurper().parseText(response.data.toString())

new File('users.csv').withWriter { writer ->
    writer.writeLine("ID,Name,Email")
    users.each { user ->
        writer.writeLine("${user.id},${user.name},${user.email}")
    }
}

println "CSV report generated!"


7. Automating Scheduled Tasks with Groovy and Cron (Linux/macOS)

Groovy scripts can be scheduled to run at specific intervals using cron on Linux/macOS. This is ideal for daily backups, log cleanups, report generation, etc.

✅ Step 1: Make Your Groovy Script Executable

Let’s say you have a Groovy script named daily-report.groovy:

#!/usr/bin/env groovy
def date = new Date().format("yyyy-MM-dd")
def report = new File("report-${date}.txt")
report.text = "Generated report on ${date}"
println "Report saved: ${report.name}"

Make it executable:

chmod +x daily-report.groovy

✅ Step 2: Schedule It with Cron

Open the crontab editor:

crontab -e

Add this line to run the script every day at 6 AM:

0 6 * * * /path/to/daily-report.groovy >> /path/to/log.txt 2>&1

Make sure the script path is absolute and that groovy is available in the environment (you might need to use the full path to groovy).


8. Packaging and Running Groovy Scripts with Dependencies

For larger Groovy automation scripts, you might want to include external dependencies like HTTP clients, JSON parsers, etc.

✅ Using Grape (Groovy's built-in dependency manager)

Add this at the top of your script:

@Grab('org.apache.commons:commons-lang3:3.14.0')
import org.apache.commons.lang3.StringUtils

println StringUtils.capitalize("groovy automation!")

Then run:

groovy script-with-deps.groovy


9. Wrapping Up: When to Use Groovy for Automation

Groovy is a strong candidate for scripting when:

  • You want the expressiveness of scripting but with Java compatibility.

  • You need to automate tasks like file manipulation, system monitoring, or reporting.

  • You want to write less boilerplate compared to Java.

  • You already use Java or the JVM ecosystem.


Conclusion and Key Takeaways

In this tutorial, you’ve learned how to:

  • Set up Groovy for scripting.

  • Automate tasks like file handling, email sending, and shell execution.

  • Schedule Groovy scripts via cron.

  • Use Grape to add dependencies.

Groovy offers a perfect balance of power and simplicity for automating repetitive tasks, especially if you're already in a JVM-based environment.

You can get the full source code on our GitHub.

That's just the basics. If you need more deep learning about Groovy and Grails, you can take the following cheap course:

Thanks!