Restarting mac using launchd

Hi

I thought I would share that I have recently solved a problem using a shell script and launchd on macOS that restarts my mac every night at 5am.

To set some context, my set up is as follows:

I have a mac running channelsdvr and a few other things. All my DVR recordings get saved onto a share on a synology NAS (it is quite old and slow, hence using the mac rather than just the NAS on its own. I have the mac set up to restart into a user that runs channels and connects to the NAS at login so that whenever it is started, the shared drive is available for channels.

The mac runs a few other things as well. Some of which stop restarts without user interaction. eg, “are you sure you want to restart” kind of alerts.

The problem I was having is that the network share would periodically disconnect. Unsure why, but as this is all running in the background and wouldn’t affect viewing of live TV, there would be no way to know there was a problem. I would log in to channelsdvr periodically and find that a week’s worth of recordings had failed which would mean a lot of repetitive deleting of jobs from the DVR schedule etc. And of course the annoyance of missing the stuff I wanted recorded.

The obvious solution would be to use the energy saver preference panel schedule. But this runs in user space and would not restart if an app prevented the restart.

The solution was to create a launch daemon that runs a shell script. This is run by the system as root and ignores any running apps. It therefore forces a restart even if something tries to prevent it.

This means my mac server is running much more reliably. Worst case is I get a days worth of missed recordings because the server will restart and reconnect to the NAS.

Considering the coding to produce the two files needed is actually quite simple and very short, it was surprisingly difficult to get it to run properly. I have described the solution here:

The solution is towards the bottom of the main post.

I’m sharing in case anyone has a similar set of problems. Hopefully it will be helpful to others.