Fix: systemd-run doesn't run correctly on Cron

In systems like Debian and Ubuntu, we have the systemd-run tool, which is part of the systemd system. One of the characteristics of this tool is the ability to control and limit system resources with quotas and limits for each service executed. There are several ways to run systemd-run, but the main reason for this entry is for those times when it does not run when using cron. Since, as many of you will know, debugging tasks in cron is a tedious and somewhat complicated task.

systemd-run help


I was using systemd-run to execute tasks such as backups and web application cron services, in the terminal they worked correctly, but when reviewing the logs, they were not being executed from the system cron.
I used systemd-run in various execution modes with a variation of the parameters, and it did not work. Furthermore, I have been trying to run the tasks with Percentage CPU Limit and IO Limit. So far everything seemed normal, the problem is, how is it possible that if a task will be correctly executed in the terminal, but in cron it fails silently?


With a little extra debugging, when checking syslog, I saw that the command logs were incomplete, they were practically in the middle, and this was what helped me find the problem. There was no real description of a problem, it was like executing half a command in cron.

Then I understood that when we use percentage symbols in tasks found in cron they must be escaped, and in this case, I was using the percentage symbol for CPU limit in systemd-run.

This is an example of my scheduled task when it failed silently.

30 */2 * * * /usr/bin/systemd-run --setenv=HOME=/root --nice 19 --pipe -p CPUQuota=70%

To escape the percent symbol, I just added a backslash before the symbol.

30 */2 * * * /usr/bin/systemd-run --setenv=HOME=/root --nice 19 --pipe -p CPUQuota=70\%

In this way everything began to function normally. The problem here was that I was unaware that certain characters needed to be escaped in the cron scheduled task lists.


It seems a simple thing, but a small error like this can take away productive days and turn them into headaches. It may have happened to me because I had never had the need to use special characters in a cron job, or maybe I miss reading the documentation of cron, in addition to the systemd-run documentation, which of course I went around trying to find the error.