Cron configuration improvements for Raspberry Pi

One of the shortcomings or RPi for (m)any serious applications is that it lacks a hardware clock so when it starts, the clock is not set correctly.

This deficiency can be overcome to some extent for some applications with the fake-hwclock module and SNTP where the RPi is always connected to a network.

The standard scheduling daemon cron does not run tasks that were missed because the system was not running at the time they were scheduled. It is a significant shortcoming that has been overcome by adding another element, anacron, which wraps the cron tasks and is scheduled by cron and at startup. All of this is very dependent on correct clock time, and for RPi systems that lack a hardware clock (the out of the box hardware), the system time can be quite wrong at the time anacron is scheduled as part of the startup procedure.

This article describes some changes to the anacron init script to improve the accuracy of anacron at startup where sntp is available.

Some additional code highlighted in green is inserted in /etc/init.d/anacron to get the time by sntp before starting anacron if fake-hwclock is in use.

case "$1" in
  start)
    if init_is_upstart 2>/dev/null; then
        exit 1
    fi
    log_daemon_msg "Starting anac(h)ronistic cron" "anacron"
    if test x"$ANACRON_RUN_ON_BATTERY_POWER" != x"yes" && test -x /usr/bin/on_ac_power
    then
        /usr/bin/on_ac_power >/dev/null
        if test $? -eq 1
        then
          log_progress_msg "deferred while on battery power"
          log_end_msg 0
          exit 0
        fi
    fi
    if [ -f /etc/fake-hwclock.data ]; then
      sntp -s pool.ntp.org
      while [ $? -ne 0 ]; do sleep 30s; sntp -s pool.ntp.org; done
    fi
    # on_ac_power doesn't exist, on_ac_power returns 0 (ac power being used)
    # or on_ac_power returns 255 (undefined, desktop machine without APM)
    start-stop-daemon --start --exec /usr/sbin/anacron -- -s
    log_end_msg 0
    ;;
  restart|force-reload|reload)

Note that if you uninstall fake-hwclock (which you would do if you install a real time clock), it does not remove the file /etc/fake-hwclock.data tested in the script, you will have to remove the file by hand so that this script works properly in that case.

Of course the best way of resolving the weakness of no hardware clock is to add one: Real time clock for Raspberry Pi.