How To Have A Custom Action Located Within An Applescript.app, Execute Only On Every Fifth Launch Of The Application

Solution 1:

You need to use a counter that lives outside the script. Create a file that hold the number of runs.

You may prepend a dot to the file name to make the file invisible.

# https://apple.stackexchange.com/questions/298264/how-to-have-a-custom-action-located-within-an-applescript-app-execute-only-on-e
# perform a command every fifth time this script is run (as an app)

set file_exists to "no"
set file_name to "oa_counter"
set file_path to POSIX path of ((path to home folder)) & file_name
set run_count to 0
tell application "Finder" to if exists file_path as POSIX file then set file_exists to "yes"

if file_exists is "yes" then
    set run_count to do shell script "cat " & POSIX path of file_path # get the current run count from the file
    do shell script "rm " & POSIX path of file_path # remove the file
end if

if run_count + 1 as number is 5 then
    display dialog "5" # do this every fifth time
else
    set run_count to run_count + 1
    do shell script "cat <<EOF >> " & POSIX path of file_path & "
" & run_count # create a new file with the new run count
    return run_count
end if

Solution 2:

You can use the modulo operator:

set number_of_runs to number_of_runs + 1
set archiveMode to number_of_runs mod 5 = 0 -- the result is true on 5, 10, 15, etc..

Instead of:

set number_of_runs to number_of_runs + 1
if number_of_runs = 5 then
    set archiveMode to true
end if