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
<?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.
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
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
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
I wanted something similar, but instead of always locking at a specific time, I wanted to lock only on certain conditions. The script I used to check those conditions was triggered by cron, so I had the same issue.
When I tried
CGSession -suspend in a cronjob, and noticed that when it was triggered, Console.app logged an error, saying only root and the current logged user could trigger a Fast User Switching. So my solution: run it as root.
So in my script, I used the following, to lock the computer:
sudo /usr/bin/osascript -e 'tell application "System Events" to do shell script "/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend"'
Convoluted? Yes. Working? Positive!