Clear History

With a large number of devices, Traccar server can quickly use up disk space available on the host machine. Main causes are positions and events in the database and daily log files.

This documentation provides a guide on how to set up automated history cleanup on a Linux server with MySQL database. The benefit of our database cleanup script is that it handles data in small batches and doesn't block Traccar server from receiving and storing new data.

Clear Database

Create cron script file:

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

With the following content

#!/bin/bash
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 -90 DAY)) AND id NOT IN (SELECT positionId FROM tc_devices WHERE positionid IS NOT NULL) LIMIT 10000")
  sleep 1
done
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 -90 DAY)) LIMIT 10000")
  sleep 1
done

And make it executable:

chmod +x /etc/cron.daily/traccar-clear-database

Make sure to adjust parameters to your use case:

It is also strongly recommended to create indexes on tc_positions.fixTime and tc_events.eventTime like this:

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

Clear Logs

The following commands will set up automatic daily cleanup of the Traccar logs:

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

Make sure to adjust the parameter to your use case: