Search code examples
shellcronsh

how to stop the cronjob after the previous success


am writing a crontab script, which will run on each Saturday for every 15minutes. The idea is to validate an external api status =SUCCESS or not. If its success, then the cronjob for the day should not trigger any more. Right now am trying with recursion, but I dont think so that is a best solution. Is there any other solution to achieve this? am using Shell script to invoke api.

Here is the existing snippet:

  • Cronjob:

    */15 * * * 6 validate.sh 
    
  • script:

    status='curl -X GET "api"' 
    if [[ $status == "SUCCEEDED" ]];then 
        trigger email
    else sleep 180 
        ./validate.sh     
    fi 
    

Solution

  • Add another cron job so it removes the flag file on Friday evening, before the other job starts running:

    59 23 * * 5 rm .succeeded.txt
    

    Then change your script so it aborts if this file exists, and creates it when it succeeds.

    #!/bin/bash
    
    test -e .succeeded.txt && exit
     
    if [[ $(curl -X GET "api") == "SUCCEEDED" ]];then 
        trigger email
        touch .succeeded.txt
    fi
    

    I tried to fix other errors in your script, too, but I had to guess many things. This assumes "SUCCEEDED" is the sole output from curl when the GET works.

    Putting the command in a variable is a useless complication which makes your script longer and (very slightly) slower, but in addition, it creates problems of its own when the command contains embedded quotes; see e.g. http://mywiki.wooledge.org/BashFAQ/050

    ... But of course, presumably you wanted to actually run the command. Your attempt would merely check whether the string in the variable was equal to "SUCEEDED" which of course it would never be.

    Another problem was that you were spawning multiple validate.sh jobs, each of which would recurse and retry. You want one or the other, not both. I went with keeping your schedule and just trying once in each job.