systemd

This is a practical example how to use systemd. There are two examples of services:

StartVM.service

[Unit]
Description=Start VirtualBox Machine and power on qnap.net
After=network.target
After=systemd-user-sessions.service
After=network-online.target
[Service]
Type=oneshot

ExecStart=/home/oscargomezf/SVN/admin/virtualbox_scripts/StartVM

StandardOutput=syslog
StandardError=syslog
[Install]
WantedBy=multi-user.target

And StopVM.service

[Unit]
Description=Stop VirtualBox Machine and power off qnap.net
Requires=network.target
After=network.target
Before=shutdown.target reboot.target halt.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStop=/home/oscargomezf/SVN/admin/virtualbox_scripts/StopVM
ExecStopPost=/bin/sleep 200
StandardOutput=syslog
StandardError=syslog
TimeoutStopSec=220
[Install]
WantedBy=multi-user.target

And these are the scripts that we are going to execute:

StartVM

#!/bin/bash
#Edit these variables!

VM_USER="oscargomezf"

VM_REDMINE="bitnami-redmine-3.3.1-0-ubuntu-14.04-x86_64"

MAC_QNAP_NET=XX:XX:XX:XX:XX:XX

#echo "Starting VirtualBox $VM_REDMINE ..."
#sudo -u $VM_USER VBoxManage startvm $VM_REDMINE --type headless
echo "Wake On Lan qnap.net: $MAC_QNAP_NET" 
powerwake $MAC_QNAP_NET
sleep 1
powerwake $MAC_QNAP_NET
sleep 1
powerwake $MAC_QNAP_NET
exit 0

StopVM

#!/bin/bash

#Edit these variables!

VM_USER="oscargomezf"
VM_REDMINE="bitnami-redmine-3.3.1-0-ubuntu-14.04-x86_64"
MAC_QNAP_NET=XX:XX:XX:XX:XX:XX
echo "Shutdown qnap.net"
/home/oscargomezf/SVN/admin/qnap_scripts/poweroff_qnap.net.sh
echo "Saving state of Virtualbox $VM_REDMINE ..."
#sudo -u $VM_USER VBoxManage controlvm $VM_REDMINE savestate
exit 0

To enable the services you have to copy the *.service files to /etc/systemd/system/ execute:

# cp *.service /etc/systemd/system/
# systemctl enable StartVM.service
# systemctl enable StopVM.service

# systemctl daemon-reload

And for logging the result you have to use:

# journalctl -xe