Linux – Is it better to use the systemd service unit’s Restart & RestartSec, or use a systemd timer unit

cronlinuxsystemdtime

I have a couple of in-house automated scripts running at periodic intervals. One is every five minutes, the other is every minute. They don't really need to be ran on-the-dot; e.g. I don't care if they run at 12:00, 12:05, etc. or at 12:03, 12:08, etc., I just need a steady interval.

Currently, I have crontab running these scripts at the specified intervals. However, on the same machine I also have custom in-house systemd service unit files. I was curious if it would be better to move my scripts to systemd service unit & timer files, or just use systemd service unit files with Restart & RestartSec directives.

Let me know if I need to rephrase something or if I'm being unclear.

Specifically, the definition for systemd.service units translates Restart=always and RestartSec=300 to be synonymous as "always run every five minutes while ignoring the exit code of the previous run". However, there's also the systemd.timer unit that could be configured to do the same but probably with specific exit codes such as successful exit only.

I'm looking for pros and cons of both.

Thanks!

Best Answer

I recommend to use a process manager to do your job. Luckily you have the best process manager ever on board, systemd. In my eyes it is about semantics, even if both solutions are working for your case.

  • Use timer units for cron-like schedules you are talking about.
  • Use restart statements to specify a restart policy of a task that ends unexpected. That means you even can define a restart policy for your timer units, in case they failed. Keep in mind that restarting units quickly enter failed states, because they quickly reach a holdoff timeout, if you don't define a RestartSec greater than 1.