How to run a script every 5 seconds only when connected to internet

internetsystemdsystemd-timer

I have a script that updates my google drive. I made a systemd unit to run this script, and a timer that runs the unit every 10 seconds, which both work. However, when I get disconnected from internet, the script fails and systemd stops running the it even if the internet comes back on. Is there any way I can make systemd keep on running the script, or is there a way to have systemd run the script only if there is an internet connection?

Here are the files

/etc/systemd/system/grive.service:

[Unit]
Description=Syncronize google drive folder

[Service]
User=my_name
ExecStart=/home/my_name/bin/update-grive

/etc/systemd/system/grive.timer:

[Unit]
Description=Timer for how often to syncronize google drive folder

[Timer]
OnUnitActiveSec=10s
OnBootSec=10s

[Install]
WantedBy=timers.target

/home/my_name/bin/update-grive:

#!/usr/bin/env bash
cd /home/my_name/gdrive
grive

Best Answer

Add Restart=always to the service unit, so systemd will keep bringing up the service if it crashes.

On a side note you should use OnUnitInactiveSec instead of OnUnitActiveSec.

OnUnitInactiveSec=10s (or 20s) will start the service 10 seconds after it stopped. This way you make sure it doesn't get called twice and possibly avoid banning for DOSing google