macOS 定时任务

在 macOS 中,可以使用 launchd 来实现定时任务。launchd 是 macOS 中的系统守护进程,它负责在系统启动时加载、启动和停止系统级服务。

要创建一个定时任务,首先需要创建一个配置文件,然后使用 launchctl 命令来加载该配置到系统中。

首先需要创建一个 launchd 的 .plist 配置文件。

下面是一个示例配置文件,它会每隔一小时使用 bash 执行一个脚本 /path/to/task.sh

<?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.example.run_task</string>
    <key>ProgramArguments</key>
    <array>
	    <string>bash</string>
        <string>/path/to/task.sh</string>
    </array>
    <key>StartInterval</key>
    <integer>3600</integer>
</dict>
</plist>

固定时间(日历)执行,使用 StartCalendarInterval
例如在每个月的第7天的13:45启动任务:

    <key>StartCalendarInterval</key>
    <dict>
        <key>Minute</key>
        <integer>45</integer>
        <key>Hour</key>
        <integer>13</integer>
        <key>Day</key>
        <integer>7</integer>
    </dict>

更多触发方式可参考:apple.com CreatingLaunchdJobs

使用 launchctl 命令将配置加载到系统中。
launchctl load /path/to/example.plist

卸载配置:
launchctl unload /path/to/example.plist

launchctl start com.example.run_task
launchctl stop com.example.run_task

列出系统当前的任务
launchctl list

参考: