Clear History

With a large number of devices, the Traccar server can quickly use up disk space. The main causes are positions and events in the database and daily log files.

This guide sets up daily cleanup on Linux with MySQL. The script deletes history in small batches so Traccar can continue receiving data. Back up your database before running it. For Microsoft SQL Server, see these instructions.

Clear Database

Create the cron script:

nano /etc/cron.daily/traccar-clear-database

With the following content:

#!/bin/bash
set -e

result=""
while [[ "$result" != *" 0 rows affected"* ]]; do
  result=$(mysql -u root -proot traccar -vve "DELETE FROM tc_events WHERE eventTime < DATE(DATE_ADD(NOW(), INTERVAL -1 YEAR)) LIMIT 10000")
  sleep 1
done

result=""
while [[ "$result" != *" 0 rows affected"* ]]; do
  result=$(mysql -u root -proot traccar -vve "DELETE FROM tc_positions WHERE fixTime < DATE(DATE_ADD(NOW(), INTERVAL -1 YEAR)) AND id NOT IN (SELECT positionId FROM tc_devices WHERE positionId IS NOT NULL) LIMIT 10000")
  sleep 1
done

Adjust the database name (traccar), username (root) and password (root). Change INTERVAL -1 YEAR in both queries to set how much history to keep. The script preserves each device's last known position and stops if a database command fails.

Make it executable:

chmod 700 /etc/cron.daily/traccar-clear-database

Indexes on tc_positions.fixTime and tc_events.eventTime can improve cleanup performance. If suitable indexes do not already exist, create them:

CREATE INDEX idx_positions_fixtime ON tc_positions (fixtime);
CREATE INDEX idx_events_eventtime ON tc_events (eventtime);

Clear Logs

Create a daily cleanup script:

cat > /etc/cron.daily/traccar-clear-logs << EOF
#!/bin/sh
find /opt/traccar/logs/ -type f -name 'tracker-server.log.*' -mtime +3 -delete
EOF
chmod +x /etc/cron.daily/traccar-clear-logs

This removes rotated logs by age and keeps the current tracker-server.log. Adjust -mtime +3 to change retention; it selects files at least four days old.