Books of Samuel
The text is presented as a prayer by David at the time he was hiding in the cave (part of the David and Jonathan narrative in the Books of Samuel). It is, consequently, used as a prayer in times of distress.