Ike348
Ike348

Reputation: 176

Mac LaunchAgent with full disk access and caffeinate

I have a script that I would like to run every day at 4 AM. It downloads data to my user folder, fits some models, and saves files within my user directory. The script is a shell script, with one Python command, followed by an R command (with Rscript), and is stored in /Library/Scripts/. It has execute permissions. Here it is:

#!/bin/sh

cd "/Users/myusername/Desktop/my/dir/with/data";

/opt/homebrew/bin/python3 download_data.py;

/Library/Frameworks/R.framework/Versions/4.1-arm64/Resources/bin/Rscript fitModels.R;

Here is my .plist file, which is stored in ~/Library/LaunchAgents and was loaded with launchctl. fdautil is a utility that allows scripts called from within LaunchAgents to be granted full disk access.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>local.myscript</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/fdautil</string>
        <string>exec</string>
        <string>/Library/Scripts/myscript.sh</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
          <key>Hour</key>
          <integer>4</integer>
          <key>Minute</key>
          <integer>0</integer>
    </dict>
</dict>
</plist>

I have also changed the setting in System Preferences to automatically wake my computer at 3:58 AM. This setup "works," except for the fact the computer goes to sleep within a few minutes after the script starts, so the script does not complete.

If I were running this script manually, I would fix this issue with caffeinate. Yet if I add <string>caffeinate</string> as the first ProgramArgument, that seems to nullify the behavior of fdautil, meaning the Python and R scripts aren't able to be executed due to permissions issues. If I add it as the third program argument (after exec), and reference it via its full path /usr/bin/caffeinate, I see You don't have permission to run this command via fdautil.

If instead I prepend caffeinate to each line in the shell script itself, the Python portion runs fine, but the R script fails in the middle of loading packages with zsh: killed caffeinate fitModels.R (the script runs fine without caffeinate, getting an explanation for this issue is probably its own question).

How can I set up this LaunchAgent to ensure that the script runs as intended, and my computer stays awake for long enough to allow it to complete?

The only alternative I can think of is to just set up another LaunchAgent that calls caffeinate -t at 4 AM and pick a long enough time such that the other script is guaranteed to finish in that time. Yet the runtime of my script can vary significantly day-to-day, and this feels like a "hacky" solution.

Upvotes: 0

Views: 258

Answers (0)

Related Questions