## Sunday, June 10, 2012

### Progamming in Stata - capture_retry (cap2)

* Basic Progamming in Stata - capture_retry (cap2)

* Sometimes when saving files especially if it is a replace command saving over repeatedly Stata can get caught up trying to save a file it just reserved write access to previously.

* One way to handle this problem would be to tell Stata to wait before saving multiple times.

* This can be done with the sleep command

* For instance

sleep 1000

* Will tell Stata to wait 1 second before going on.

* However, this has its own obvious cost in time.

* An alternative would be the following command which tells Stata to retry the command up to attempts', pausing for 1/100 of a second between attempts.

** Write a small program to be used to retry code.
cap program drop cap2
program define cap2

* This tells stata to run whatever code is input into the cap2 command.
* 0' is the entire contents of the input after the command's call.
cap 0'

* This is a parameter that tells stata how many times to make the attempt
local attempts=50

* The _rc is a local that capture creates that gives an error != 0 if there are any problems with the capture command and == 0 if the command was executed successfully.
while _rc != 0 & 0i'&lt;attempts'-1 {
local i=0i' + 1
* Keep track of how many times the command was attempted
cap 0'
* Attempt the command again
sleep 10
* Pause for 1/100 of a second between each attempt
}
* If the count equals the number of attempts' then the command has failed and the following code displays and error.
if 0i'==attempts' {
di _c as error "Command failed after attempts' attempts : "
di as input "0'"
}
end
* End the cap2 program definition

cap2