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

如何使用Automator监听Mac指定通知并执行退出应用等操作?

Mac 监听特定通知执行操作的实现方案

Automator 原生能力说明

Automator 没有提供原生的系统通知监听动作,无法直接在 Folder Action 工作流中添加监听通知的原生步骤。

可行落地方案

方案1:AppleScript 监听通知(通用场景)

可以调用 macOS 内置的 UserNotifications 框架实现通知监听,脚本可以单独运行,也可以打包为 Automator 应用长期后台驻留:

use framework "UserNotifications"
-- 下方参数替换为你自己的实际配置
set targetAppName to "备份应用的名称"
set notificationKeyword to "备份完成" -- 通知标题/正文中包含的关键词

on receiveNotification:(notification)
    set triggerApp to notification's bundleIdentifier() as text
    set notiTitle to notification's title() as text
    set notiBody to notification's body() as text
    -- 匹配到目标应用和关键词后退出应用
    if triggerApp contains targetAppName and (notiTitle contains notificationKeyword or notiBody contains notificationKeyword) then
        tell application targetAppName to quit
    end if
end receiveNotification:

-- 注册通知监听
set notifyCenter to current application's UNUserNotificationCenter's currentNotificationCenter()
notifyCenter's setDelegate:me
-- 保持脚本运行
repeat
    delay 60
end repeat

注意:首次运行需要在「系统设置 > 隐私与安全性 > 通知」中给脚本/Automator 应用开放通知权限。

方案2:Folder Action 内嵌轮询逻辑(适配你的场景,更稳定)

由于备份应用是你自己通过 Folder Action 启动的,不需要依赖通知监听,可以直接在原有工作流中添加进程状态轮询逻辑,识别到任务完成后自动退出应用,不需要额外驻留进程:

  1. 打开你原有的 SD 卡插入触发的 Folder Action 工作流
  2. 在「启动备份应用」的步骤后,添加「运行 AppleScript」动作
  3. 粘贴如下代码,替换对应参数即可:
set targetApp to "你的备份应用名称"
-- 等待应用启动完成
delay 10
repeat
    -- 检测应用是否仍在运行
    if not (application targetApp is running) then exit repeat
    -- 读取应用CPU占用率,判断是否处于闲置状态(任务已完成)
    set cpuUsage to do shell script "ps aux | grep -i '" & targetApp & "' | grep -v grep | awk '{sum += $3} END {print sum}'"
    try
        if (cpuUsage as number) < 2 then
            -- 连续两次检测CPU占用低于阈值,判定任务完成
            delay 15
            set cpuUsageCheck to do shell script "ps aux | grep -i '" & targetApp & "' | grep -v grep | awk '{sum += $3} END {print sum}'"
            if (cpuUsageCheck as number) < 2 then
                tell application targetApp to quit
                exit repeat
            end if
        end if
    end try
    -- 轮询间隔,可自行调整
    delay 30
end repeat

注意事项

  • 如果你能拿到备份应用的进程名、备份输出目录的特征,还可以把轮询逻辑改成检测备份文件是否生成完毕,判断逻辑更准确。
  • 方案2不需要额外申请通知权限,和你现有Folder Action的适配性更高,优先推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:48:01