Archive for February, 2015

Exiting script mid-way – gracefully (with a die-file)
0Why I never thought of this before, I don’t know. But this is saving my bacon right now:
The scene:
I have a script that does 10 000 things on each loop on my DB. Unfortunately, because of the architecture that I’m interacting with, I can’t wrap the entire thing in a transaction. If I could, then killing the script mid-way will have no negative effect on the db, because it’ll just roll back the whole thing.
However, killing the script in the middle having it non-transactionalised, introduces a whole range of negative side-effects – life for instance inflating the summary data I’m building.
Anyways, forget the above, it doesn’t matter.
All I want to do is to “tell my script” that I’d like it to quit after the current iteration of the loop.
My solution: Give it a “die file”.
Say for instance my script’s name is “maintenance20150216.php”
I put the following code inside it:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$dieFile = basename(__FILE__).'.die'; while (true) { // do some awesome stuff here, for instance a chunk of work // killing the script here would have a negative effect!! // do some more stuff if (file_exists($dieFile)) { die($dieFile.' exists. Exiting gracefully!'); } } |
Cool thing about this? All I got to do while the script is running:
1 |
touch maintenance20150216.php.die |
This in turn creates the “die file”, which tells the script to quit after the next iteration of the loop.
This way I don’t have to kill or ctrl-c the script and risk it quitting at the wrong place inside the loop. My script can run for it’s calculated days of processing, and if I need to make a change – or at the very least have it back off for a bit to give the DB a breather, I can do so easily and safely now.