You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac下通过launchd自动执行Shell脚本实现定时强制重启

解决Mac每日定时强制重启(绕过应用阻止)的launchd配置问题

作为Shell脚本和launchd的新手,我之前尝试实现Mac每日定时强制重启——因为系统节能偏好里的定时重启会被运行中的应用阻止,而终端的shutdown命令可以强制重启,但过程中踩了不少坑:

遇到的问题

  • 一开始用BBEdit编写的.plist文件无法加载到launchctl,换成Xcode编辑后能加载了,但执行脚本时抛出异常代码1;不过手动执行脚本是可以正常重启的。
  • 尝试把文件权限改成root:wheel后,错误变成了异常代码78。
  • 给脚本添加日志输出后,报错提示只读文件系统,这才想到可能和macOS Catalina的只读系统分区有关。

最终解决方案

经过调试,终于搞定了,步骤如下:

  • 将最终的.plist文件放在/Library/LaunchDaemons目录下,脚本放在/Library/Scripts目录;
  • 用sudo chown root [plist文件名]修改plist文件的所有权为root;
  • 必须以root身份加载plist:sudo launchctl load [plist文件名],之后要查看这个服务的话,得用sudo launchctl list才能看到;
  • 配置完成后,就能实现每日定时强制重启,完全忽略那些阻止重启的应用。

相关代码示例

重启脚本内容

#!/bin/bash
date +"%F %T Shutting down"
/sbin/shutdown -r now

对应的launchd 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.erithacus.restart</string>
<key>Program</key>
<string>/Library/Scripts/com.erithacus.restart.sh</string>
<key>StandardOutPath</key>
<string>/tmp/com.erithacus.restart.stdout</string>
<key>StandardErrorPath</key>
<string>/tmp/com.erithacus.restart.stderr</string>
<key>StartCalendarInterval</key>
<dict>
<key>Hour</key>
<integer>12</integer>
<key>Minute</key>
<integer>10</integer>
</dict>
</dict>
</plist>

内容的提问来源于stack exchange,提问作者Erithacus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:02:57