0
[Unit]
Description=captive portal automation

[Service]
Type=simple

ExecStart=/usr/bin/python /home/pi/do.py
Restart=on-failure
RestartSec=5

The above is the content of a systemd service called caportal.service running on an Ubuntu 14.04 machine. I need to repeat the service for every 30 minutes. How can i do that ?

/home/pi/do.py

import requests,json
import netifaces as ni
import commands as cm


gateway=ni.gateways()['default'][ni.AF_INET][0]

IPaddr=ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']
mac=ni.ifaddresses('wlan0')[ni.AF_LINK][0]['addr'].upper().replace(':','-')
ssid=cm.getoutput('iwgetid -r')
Home="http://"+gateway+":8010/"

URL=Home+"login.html"
print URL
d={}
d['IdSession']=mac
d['Language']='English'
d['refrescar']='0'
d['ip']=IPaddr
d['mac']=mac
d['DSP']=Home
d['AC']='1'
d['userlog']='vishnu'
d['userpass']='12345'
d['read']='checkbox'
d['Login']='+++Go+++'

try:
    if ssid=='machCochin':
        r=requests.post(URL,data=d)
        print r.status_code
        #raise ValueError("ERROR simulated")
    else:
        print "network is not machCochin"
except Exception as e:
    pass
1
  • Have you considered using cron for it? That's probably simpler. Or make a script that does it, sleeps for 30 minutes, and repeats it? Then you could run the script as a service... – vidarlo May 3 '19 at 9:34
3

systemd provides an ananalog of the cron jobs. They are called timer.

You need to create both a .service file to run your script and a .timer file with matching filename to schedule it.

Something like:

[Unit]
Description=run my script

[Timer]
OnCalendar=*-*-* *:00/5:05
Persistent=true

[Install]
WantedBy=timers.target

To run every 5 minutes for example. I let you dig the man page or you search engine to look the OnCalendar directive or others too.

You can even run as a user by placing both files in ~/.config/systemd/user/ or as root in /etc/systemd/system

You need activate the timer to get it running after you reboot

sudo systemctl enable myservice.timer

Add --user to the command above (and without sudo) if you run as a user from ./config

Then, run it with

sudo systemctl start myservice.timer

or

systemctl --user start myservice.timer
1
  • How would use configure this to persist through a reboot? I've followed the docs, but it does not seem to work. – Martin W May 23 '19 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.