¿Cómo puedo configurar un servicio systemd para que se reinicie periódicamente?


Tengo un servicio systemd simple que necesita ser reiniciado periódicamente para evitar que su proceso se desconecte. ¿Existe una opción de configuración para que los servicios systemd los reinicien periódicamente? Todos los Restart* las opciones parecen referirse a reiniciar el servicio cuando se cierra.

Author: wes, 2015-06-25

5 answers

Sí, puede hacer que su servicio lo reinicie periódicamente haciendo su servicio de Type=notify. Agregue esta opción en la sección [Servicio] de su archivo de servicio junto con Restart=always y dé WatchdogSec=xx, donde xx es el período de tiempo en segundo lugar que desea reiniciar su servicio. Aquí su proceso será asesinado por systemd después del período de tiempo xx y será reiniciado por systemd nuevamente. por ejemplo.

[Unit]
.
.

[Service]
Type=notify
.
.
WatchdogSec=10
Restart=always
.
.

[Install]
WantedBy= ....
 23
Author: Saturn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-13 04:12:00

Vi una solución aquí que parecía elegante, aunque un poco rotonda. La idea clave es crear un servicio de una sola vez activado por un temporizador que reinicia otro servicio.

Para el temporizador:

[Unit]
Description=Do something daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timer.target

Para el servicio one-shot:

[Unit]
Description=Restart service

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl try-restart my_program.service

Para el servicio one-shot en Ubuntu 16.04 LTS:

[Unit]
Description=Restart service

[Service]
Type=oneshot
ExecStart=/bin/systemctl try-restart my_program.service

Esta solución le permite aprovechar los temporizadores de systemd, incluida la capacidad de reiniciar el servicio a una hora particular del día, y no solo después de cierta cantidad de tiempo ha transcurrido.

 19
Author: matmat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-06 20:46:42

Esto puede no haber estado presente en el momento en que se hizo la pregunta, pero ahora hay una opción llamada RuntimeMaxSec, que termina el servicio después de que ha estado funcionando durante el período de tiempo dado.

Por ejemplo

[Service]
Restart=always
RuntimeMaxSec=604800

A mí esto me parece más elegante que abusar Type=notify y WatchdogSec.

 19
Author: Alex Forbes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-14 14:01:46

¿Qué tal un crontab como

30 3 * * sun /bin/systemctl restart yourService

Que reiniciaría el servicio yourService a las 3:30am cada domingo.

 4
Author: Fritz Zaucker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-28 06:09:36

Solo algunos enfoques alternativos para alcanzar finalmente el mismo objetivo:

  • si tiene control sobre la implementación del servicio, podría hacer que finalice voluntariamente después de un tiempo, por ejemplo, saliendo de forma simple después de un cierto número de iteraciones (si corresponde) o usando un temporizador de tiempo de espera con un controlador sendin en sí mismo un SIGTERM/SIGKILL
  • si la finalización del servicio voluntario no es factible/práctica, podría tener un pequeño script basado en cron que mataría el(los) proceso (s) de servicio.
 3
Author: Dan Cornilescu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-25 17:22:43