Skip to content

hs.fs.volume.eject is not executed at hs.caffeinate.watcher.systemWillSleep event #3742

@mrdc

Description

@mrdc

Hello,

I'm trying to do some pre-sleep tasks when my MacBook goes to sleep. Especially, unmount several remote volumes, but hs.fs.volume.eject("/Volumes/SomeVolume") is not executed at hs.caffeinate.watcher.systemWillSleep event.
Initially, I've tried this and the unmount wasn't successful:

function caffeinateWatcher(eventType)
    if (eventType == hs.caffeinate.watcher.systemWillSleep) then
            print ("Executing pre-Sleep tasks...")
            -- Execute sleep script
            hs.task.new("/Users/user/.sleep", nil):start():waitUntilExit()
            --hs.task.waitUntilExit()
    elseif (eventType == hs.caffeinate.watcher.systemDidWake) then
            print ("Executing after-Wake tasks...")
            -- Execute wake script
            --hs.task.new("/Users/user/.wakeup", nil):start()

    end
end

sleepWatcher = hs.caffeinate.watcher.new(onSystemSleep)
sleepWatcher:start()

.sleep:

#!/bin/bash
caffeinate -i diskutil unmount "/Volumes/SomeVolume"

# or

diskutil unmount "/Volumes/SomeVolume"

This also failed:

local function ejectVolume(volumeName)
    local ejectTask = hs.task.new("/usr/sbin/diskutil", function(exitCode, stdout, stderr)
        if exitCode == 0 then
            hs.notify.new({
                title = "Volume Ejected",
                informativeText = "Successfully ejected volume: " .. volumeName
            }):send()
        else
            hs.notify.new({
                title = "Eject Failed",
                informativeText = "Failed to eject volume: " .. volumeName .. "\nError: " .. stderr
            }):send()
        end
    end, {"unmount", volumeName})

    ejectTask:start()
end

Using AppleScript also failed:

hs.osascript.applescript([[
        tell application "Finder"
                eject disk SomeVolume
        end tell
    ]])

Is it possible to delay going to sleep and execute all tasks triggered by the systemWillSleep event?

macOS Sonoma 14.7.2
Hammerspoon 1.0.0 (6864)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions