Ubuntu – Using upstart for non-daemon tasks

shutdownstartupupstart

I would like to have foo do-startup-things run on boot, and foo do-shutdown-things run on shutdown where foo is my own program.

It looks like Upstart is a good candidate to do this, but Upstart seems to be designed for use with daemons, so running service foo stop gives the error stop: Unknown instance: because the process executed when the startup job was run is no longer running.

Is there a way to use Upstart to execute tasks on startup and shutdown without starting a daemon?

Best Answer

Yes, it is possible. You should define two task job, here is an example:

First create startTaskJob.conf:

# startTaskJob - 
#
# This service print "script start" and end 
description "print script start"
start on runlevel [2345]

task
console log
script
  exec  echo "script start"
end script

You can test it with:

sudo start startTaskJob

and the output will be saved in /var/log/upstart/startTaskJob.log

Than create stopTaskJob.conf:

# stopTaskJob - 
#
# This service print "script stop" and end 
description "print script stop"
start on runlevel [016]

task
console log
script
  exec  echo "script stop"
end script

This script will be executed every time system enter in runlevel 0, 1 or 6. At shutdown runlevel become 0 and upstart init process will run it because of "start on runlevel [016]".

You can test it:

sudo start stopTaskJob

UPDATE: This is an example on how to do this in a single file.

# taskJob - 
#
# This service print environment variable 
# start on runlevel 
description "print environment variable"
start on runlevel [0123456]
task
console log
script
if [ "$RUNLEVEL" = "0" -o "$RUNLEVEL" = "1" -o "$RUNLEVEL" = "6" ]; then
    exec  echo "(stopTask) $UPSTART_EVENTS - $RUNLEVEL - job $UPSTART_JOB" 
else
    exec  echo "(startTask) $UPSTART_EVENTS - $RUNLEVEL - job $UPSTART_JOB"
fi
end script

I tested it on lubuntu 12.04 and this is /var/log/upstart/taskJob.log content after restart:

(stopTask) runlevel - 6 - job taskJob
(startTask) runlevel - 2 - job taskJob
Related Question