Skip to main content
  1. Posts/

Cleanup old files and directories with Systemd/Timers

··255 words·2 mins·

It is very easy to setup Reolink camera (and probably every other brand) to upload recordings to an FTP server. After some time you notice that nothing new arrives on your FTP from the camera as disk filled up. You clean up old ones manually and don’t want to repeat that ever again. Systemd/Timers to the rescue.

We are going to use find command to indentify files that are older than 15 days and delete them:

$ find /srv/ftp/Reolink -ctime +15 -type f -delete
$ find /srv/ftp/Reolink -type d -empty -delete

First one deletes files, second one all empty directories left behind.

As an admin create two files /etc/systemd/system/camera-cleanup.service and /etc/systemd/system/camera-cleanup.timer:

# /etc/systemd/system/camera-cleanup.service
[Unit]
Description="Camera recordings cleanup (15 days and older)"

[Service]
ExecStart=/bin/bash -c "find /srv/ftp/Reolink -ctime +15 -type f -delete && find /srv/ftp/Reolink -type d -empty -delete"
# /etc/systemd/system/camera-cleanup.timer
[Unit]
Description=Run Camera cleanup daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

Timer is configured to run on daily basis. It triggers the service that runs our bash commands to cleanup old file and empty directories. To enable and start the timer just run:

$ sudo systemctl enable camera-cleanup.timer
$ sudo systemctl start camera-cleanup.timer
$ sudo systemctl status camera-cleanup.timer
● camera-cleanup.timer - Run Camera cleanup daily
     Loaded: loaded (/etc/systemd/system/camera-cleanup.timer; enabled; preset: disabled)
     Active: active (waiting) since Sat 2024-01-20 16:55:54 UTC; 42min ago
    Trigger: Sun 2024-01-21 00:00:00 UTC; 6h left
   Triggers: ● camera-cleanup.service

Jan 20 16:55:54 myserver systemd[1]: Started Run Camera cleanup daily.

That is it! That way you can automate many other tasks on your Linux server.