scheduled account lock Mac OS X

You can set your Mac OS X account to automatically lock the screen so that the password is required after a certain amount of time of inactivity, but can you do the same thing using a schedule (say at 5:30 PM every day)? Kind of like how you can have the computer turn on/off or go to/wake up from sleep at a certain time.


You can use launchd to do this. Place the following xml into a new text file in ~/Library/LaunchAgents/ and call it something descriptive with a suffix of .plist. For example, mine is ~/Library/LaunchAgents/logoutAt1730.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>Logout At 5:30 PM</string>
        <key>ProgramArguments</key>
        <array>
            <string>/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession</string>
            <string>-suspend</string>
        </array>
        <key>StartCalendarInterval</key>
        <dict>
            <key>Hour</key>
            <integer>17</integer>
            <key>Minute</key>
            <integer>30</integer>
        </dict>
    </dict>
    </plist>

If you want it to run on the current power cycle (Eg you don't want to restart for this to take effect) use launchctl load ~/Library/LaunchAgents/logoutAt1730.plist to tell launchd about the new item. It should load automatically next time you login.

Use launchctl list and look for the label string (Logout at 5:30 PM) to validate that launchd knows about the item.

I have verified this works on my workstation. I don't know why cron doesn't.


EDIT: Although I am not certain of why cron fails to work for this specific use-case, this answer is superceeded by the (currently more correct) answer using launchd.

Use crontab -e in the terminal application to add /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend to the Crontab at the appropriate time, like so (for 5:30 PM):

30 17 * * * /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend