How can I automatically eject volumes I no longer use?

I have a volume (saved as an encrypted sparsebundle) that I use from time to time. For security reasons it should be ejected when not in use. Of course I should do it myself, and usually I remember. But not always. Is there an automated way to do this as a back-up for fallible me?

Maybe a Folder Action attached to it that will eject it after a certain length of time (or even better, a certain length of time idle) or at a certain time of day?

Maybe a way to have it automatically ejected when the computer sleeps? Currently, it is still there after computer sleep. (I don't want to use logout because there are other processes I want to keep going.)


Thanks to patrix, I now have it working. I will post something here for others who want to do this in the future.

It seems that cronjob is no longer recommended, instead launchd. This was the first time I wrote a launch agent, so there were many errors before I got it to work. I could not decipher the error messages in the System log, but at least when they were there it told me it was not working.

I found a tutorial for a launch agent on robots.thoughbot.com. Some of the ways he uses launchctl are marked "legacy" by Apple, but they still worked for me in Sierra.

Here is my launch agent plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.gae.umount1</string>
    <key>ProgramArguments</key>
    <array>
        <string>diskutil</string>
        <string>unmount</string>
        <string>force</string>
        <string>/Volumes/3D</string>
    </array>
    <key>StartInterval</key>
    <integer>10800</integer>
</dict>
</plist>

It is supposed to execute the Unix command diskutil unmount force /Volumes/3D every 10800 seconds (= 3 hours).