Course contentsShow
← Linux
Lesson 1279 of 1,81911. Automation and System SchedulingFree lesson

Resource Constraints in Timer Units

Apply Cgroup-based resource limits to systemd timer-invoked services.

In this lesson, you will learn how to prevent periodic automation tasks from consuming excessive system resources by applying cgroup limits directly to your systemd services.

When you use systemd timers to trigger background tasks, those tasks run as service units. Without constraints, a runaway script or a particularly heavy batch job could consume all available CPU or memory, potentially degrading the performance of your primary applications or the OS itself. Since timers decouple the scheduling from the execution, we apply resource limits to the .service unit triggered by the timer, not the .timer unit itself.

Applying Resource Controls

Systemd leverages Linux Control Groups (cgroups) to enforce these boundaries. You define these limits within the [Service] section of your service file. By applying these settings, you ensure that even if a job encounters an infinite loop or a memory leak, its impact remains localized within the cgroup.

Consider a daily log-compression job. To ensure it doesn't starve other processes of memory or CPU cycles, you might configure it as follows:

[Service]
Type=oneshot
ExecStart=/usr/local/bin/compress_logs.sh
# Limit to 50% of a single CPU core
CPUAccounting=true
CPUQuota=50%
# Limit memory usage to 256MB
MemoryAccounting=true
MemoryMax=256M

Why Service-Level Control Matters

While you might be tempted to use nice or ionice inside your shell scripts, these only adjust process priority; they do not provide hard ceilings. By defining MemoryMax or CPUQuota in the service unit, you provide the kernel with an explicit instruction to throttle or kill the process if it exceeds the boundary.

Because the timer unit simply executes this service, the timer remains "clean" and focused only on scheduling, while the service carries the weight of execution constraints. This approach is superior to older methods like cron because the limits are enforced by the init system itself, providing consistent behavior regardless of the user account or environment variables under which the script runs.

Key Takeaway: Use systemd service units to wrap timer-triggered tasks, applying cgroup-based resource constraints like MemoryMax and CPUQuota to ensure background automation does not negatively impact system stability.