You can do this with a simple bash script, the
uptime command and
launchd. If you execute the command by itself, it will tell you how long the machine has been up:
6:08 up 20 days, 21:09, 4 users, load averages: 1.09 1.29 1.36
So, the number that we are interested is the "20" which we will evaluate against our condition of "1 day"
#Maximum number of days to be up
#Get the uptime days and assign it to a variable
uptime_days=`uptime | cut -d " " -f 5`
if [ $uptime_days -ge $max ]
shutdown -h now
Make sure you set the script as executable or it won't run:
chmod +x shutdown24.sh
Now, here's the most important part. When do you want to evaluate this? Technically, your could have this script run every hour (or even ever minute) to evaluate if the computer has been up for 24 hours.
This is not recommended because if for some reason the computer was turned on at 10:00am (because the person was late, for example) you don't want it shutting down at 10:00am the next morning when they are in the middle of their work.
So, I'm going to assume you want it run at midnight so you don't inadvertently shutdown the machine while people are working. What you need is to utilize
lauchd and create a
.plist that defines the job (similar to Task Scheduler) in Windows.
Let's assume that we called the bash script
shutdown24.sh so we will call our .plsit
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
Copy this file to
/Library/LaunchDaemons and then load it to
sudo launchctl load com.user.shutdown24.plist
The job will be run as root and at 12:00am every morning, it will check if the system uptime and will shutdown if it's greater than 24 hours.