Search code examples
macosbashcronstartuplaunchd

Run a shell script periodically on Mac OS X without root permission


I want to start up a file with .sh type or .py on mac os x without using root , I searched in google and found launchctl can help me ,

so i read tutorial and do same in tutorial but it not work for me , [i using mac os x 10.9 x64]

My .plist file [run 1.sh file in every 60second] :

<?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.alvin.crontabtest</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Users/paul/Desktop/1.sh</string>
  </array>
  <key>Nice</key>
  <integer>1</integer>
  <key>StartInterval</key>
  <integer>60</integer>
  <key>RunAtLoad</key>
  <true/>
  <key>StandardErrorPath</key>
  <string>/tmp/AlTest1.err</string>
  <key>StandardOutPath</key>
  <string>/tmp/AlTest1.out</string>
</dict>
</plist>

source of 1.sh:

echo '+' >> /Users/paul/Desktop/worked.txt

I put Run.plist in /Users/paul/Run.plist

and run command from terminal :

launchctl load /Users/paul/Run.plist
Launchctl start com.alvin.crontabtest

commands execute without any error but i not see anything in worked.txt

can anyone help me please ?


Solution

  • Any particular reason you don't want to use a normal crontab?

    % echo "* * * * * /Users/paul/Desktop/1.sh" | crontab -
    

    This command should add a cron job that runs once per minute.

    NOTE that this command will also replace any crontab that you already have. The crontab - command should be used with caution, as a short-cut.

    If you want to edit an existing crontab, so as to avoid obliterating previously set jobs, you can use crontab -e. (If it launches vim and you don't know how to use vim, you can exit by hitting ESC:q!Enter and then go find editor documentation.)

    If you want instructions on how to edit crontabs, type man crontab at your shell. If you want syntax information on the crontab file, man 5 crontab will show you that.

    Enjoy!


    UPDATE: (per comments)

    To run your job every 30 seconds requires a simple hack. Cron only runs jobs on a per minute basis, so to run things every 30 seconds, you can have two jobs, one of which has a 30 second delay. For example:

      #Mn Hr Da Mo DW Command
      *   *  *  *  *   /Users/paul/Desktop/1.sh
      *   *  *  *  *   sleep 30; /Users/paul/Desktop/1.sh
    

    Hope this helps.