P
P
password222022-01-09 00:51:09
ubuntu
password22, 2022-01-09 00:51:09

How to restart service in crontab ubuntu?

A bunch of articles and videos on how to run crontab in ubuntu, a script and so on.

But how do I restart my own service, i.e. the service that is responsible for the site?

I tried

sudo crontab -e
добавила туда 0 4 * * * sudo systemctl restart mySite.service


Then I tried
sudo nano /etc/cron.hourly/testHourly
0 4 * * * sudo systemctl restart mySite.service

I don't really understand how to restart the service once a day...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
password22, 2022-01-11
@password22

In my case, this is what I had to do.
To restart the site on asp.net by timer, I had to create a separate timer + service + restart script.
That is, in the end it should be:

  1. site.service - site launch service itself
  2. siteRestart.service - service referring to restart script
  3. siteRestart.timer - timer for restart service
  4. siteRestart.sh - restart script

site.service
[Unit]
Description=Example .NET Web API App running on Ubuntu

[Service]
WorkingDirectory=/var/www/helloapp
ExecStart=/usr/bin/dotnet /var/www/helloapp/helloapp.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

siteRestart.service
[Unit]
Description=siteRestartService

[Service]
Type=simple
ExecStart=/usr/local/bin/siteRestart.sh

[Install]
WantedBy=multi-user.target

siteRestart.timer
[Unit]
Description=RestartSiteDaily

[Timer]
OnCalendar=daily
Unit=siteRestart.service
Persistent-true

[Install]
WantedBy=multi-user.target

siteRestart.sh
#!/bin/bash
systemctl restart site.service

next
sudo chmod 744 /usr/local/bin/siteRestart.sh
sudo chmod 644 /etc/systemd/system/siteRestart.service
sudo systemctl daemon-reload
sudo systemctl start siteRestart.service siteRestart.timer
sudo systemctl enable siteRestart.service siteRestart.timer
sudo systemctl status siteRestart.service siteRestart.timer That's
the only way it worked!

V
Valdemar Smorman, 2022-01-09
@smorman

Setting up a timer and enjoying life...
Setting up systemd timers instead of cron jobs
Systemd, interactive scripts and timers
Using systemd timers instead of cron jobs

D
Drno, 2022-01-09
@Drno

sudo crontab -e
0 0 */1 * * systemctl restart mySite.service
minutes hours day month year
0 minute - 0 hour - *(every)/1(one) day - * (any week) - * (any month)
here so at 23:30 every day
30 23 */1 * *
if the script needs to be run from sudo, then you need to add it to the rootA cron, and not to your user one. because the script with sudo rights from cron will not run it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question