Skip to content

Instantly share code, notes, and snippets.

@JaneJeon
Last active June 25, 2025 02:31
Show Gist options
  • Select an option

  • Save JaneJeon/2988d8da093861eb60ec2d2e13d4e788 to your computer and use it in GitHub Desktop.

Select an option

Save JaneJeon/2988d8da093861eb60ec2d2e13d4e788 to your computer and use it in GitHub Desktop.
All You Need Are Timeouts
#!/bin/bash
echo "----- $(date) -----"
current_hour=$(date +"%H")
current_minute=$(date +"%M")
hour_int=$((10#$current_hour))
minute_int=$((10#$current_minute))
if (( hour_int % 4 == 0 )); then
break_minutes=15
elif (( hour_int % 2 == 0 )); then
break_minutes=10
else
break_minutes=5
fi
echo "Current hour: $hour_int, current minute: $minute_int"
echo "Break length this hour: $break_minutes minutes"
if (( minute_int < break_minutes )); then
echo "Status: INSIDE break period"
loggedInUser=$(stat -f "%Su" /dev/console)
loggedInUID=$(id -u "$loggedInUser")
loginwindow_pid=$(pgrep -nx -u "$loggedInUser" loginwindow)
echo "Launching screen saver as user $loggedInUser (UID $loggedInUID), loginwindow PID: $loginwindow_pid"
if [[ -n "$loginwindow_pid" ]]; then
echo "Locking screen using pmset..."
# Use su to run pmset as the actual user - this works reliably
if su - "$loggedInUser" -c "pmset displaysleepnow" 2>/dev/null; then
echo "Display locked successfully"
else
echo "Failed to lock screen - pmset error"
fi
else
echo "ERROR: No loginwindow process found for $loggedInUser"
fi
else
echo "Status: OUTSIDE break period"
fi
<?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.local.enforcebreak</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/enforce_break.sh</string>
<string>runAsUser</string>
</array>
<key>StartInterval</key>
<integer>30</integer>
<key>RunAtLoad</key>
<true/>
<key>StandardOutPath</key>
<string>/tmp/enforcebreak.log</string>
<key>StandardErrorPath</key>
<string>/tmp/enforcebreak.err</string>
</dict>
</plist>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment