In this article, we will walk through the process of creating and setting up a custom systemd timer to clean a database on a Debian 10 machine weekly. Systemd is a system and service manager for Linux systems, which allows for managing and controlling various services and processes. With systemd, you can easily create your custom timers and services to automate tasks.
Prerequisites
To follow this guide, you need to have a Debian 10 machine with sudo privileges.
Creating the Service File
The first step is to create a service file that will clean the database. For this example, we will create a simple bash script that cleans up the database and place it in the /opt/db-cleanup directory.
Create a new file called clean-db.sh in /opt/db-cleanup, using your favorite text editor, and add the following content:
#!/bin/bash
# This script cleans up the database
echo "Starting database cleanup..."
# Replace the following line with your actual database cleanup command
echo "Database cleaned up successfully."
Next, give the script executable permissions:
sudo chmod +x /opt/db-cleanup/clean-db.sh
Now, create the systemd service file. In your text editor, create a new file called /etc/systemd/system/db-cleanup.service and add the following content:
[Unit]
Description=Database Cleanup Service
[Service]
Type=simple
ExecStart=/opt/db-cleanup/clean-db.sh
User=root
Group=root
StandardOutput=syslog
StandardError=syslog
Restart=on-failure
[Install]
WantedBy=multi-user.target
Save and close the service file, then reload the systemd daemon to apply the new service:
sudo systemctl daemon-reload
Creating the Timer File
Next, create the systemd timer file that will trigger the service we created above. Create a new file called /etc/systemd/system/db-cleanup.timer and add the following content:
[Unit]
Description=Weekly Database Cleanup Timer
[Timer]
OnCalendar=weekly
Persistent=true
[Install]
WantedBy=timers.target
Save and close the timer file, then reload the systemd daemon and enable the timer:
sudo systemctl daemon-reload
sudo systemctl enable db-cleanup.timer
To start the timer immediately instead of waiting for the next weekly schedule, run:
sudo systemctl start db-cleanup.timer
Checking the Timer and Service Status
You can check the status of the timer and the service with the following commands:
sudo systemctl list-timers --all
sudo systemctl status db-cleanup.service
- We have created a custom systemd service to clean a database and placed it in a new directory, /opt/db-cleanup.
- A systemd timer has been set up to trigger the service weekly.
- The timer and service have been enabled and started.