πŸ“˜ Guide: Automating a Perl Script Using systemd Timers on Debian

Date Created: 2025-04-18
By: 16BitMiker
[ BACK.. ]

This guide walks you through how to run a Perl script on a regular schedule using systemd services and timers on a Debian-based system. We'll use a real-world example: a script that updates the modification time of HTML files based on embedded date strings.

Whether you're automating a blog, syncing timestamps, or just learning systemd, this guide will help you build a reliable and maintainable timer-based setup using best practices.

πŸ“‹ What the Perl Script Does

The script in question, touch.pl, lives in:

🧠 Purpose

It performs the following:

This is ideal for workflows where you want ls -lt to show logical, content-driven update times rather than filesystem timestamps.

πŸ“¦ Perl Script with Comments

Here’s the script with detailed commentary:

πŸ› οΈ Preparing the Script

Before systemd can run the script:

  1. Ensure it’s executable:

  2. Make sure all parent directories are executable (searchable) by systemd:

  3. Consider ownership:

    • You can safely run it as root, or

    • Run it as www-data if permissions allow (discussed later)

βš™οΈ Creating the systemd Service

A service defines how your script runs.

Create the service unit at /etc/systemd/system/touchpl.service:

πŸ” Why This Works

⏱️ Creating the systemd Timer

This defines when the service will run.

Create the file /etc/systemd/system/touchpl.timer:

πŸ”„ Timer Settings Explained

You can change OnCalendar to daily, weekly, or even a custom format like OnCalendar=Mon..Fri 08:00.

▢️ Enabling and Starting the Timer

Once both files are in place:

This enables the timer at boot and starts it immediately.

βœ… Verifying the Setup

πŸ“… Check Scheduled Runs

This shows when it last ran, when it will next run, and its active state.

πŸ“– Check Logs

Or see real-time output:

πŸ§ͺ Test Manually

You don’t have to wait for the next timer tick. Run it manually:

You can confirm success via file timestamps or by checking the logs.

πŸ‘€ Optional: Run as a Limited User

If you don’t want this job running as root, and the script’s directory/files are readable and writable by the web user, add this to the service:

Ensure necessary access:

πŸ“ Optional: Write Logs to a File

If you want logs outside of journalctl, modify the service:

Create the log file and set permissions:

πŸ”š Summary Table

StepDescription
βœ… Script in place/var/www/scripts/touch.pl
βœ… Made executablechmod +x
βœ… Created systemd servicetouchpl.service
βœ… Created systemd timertouchpl.timer
βœ… Enabled the timersystemctl enable --now
βœ… Verified behaviorvia list-timers, journalctl

Your Perl timestamp script is now fully integrated into systemd and running automatically each hour. πŸ•

πŸ“š Read More