As the fish's odd behavior is not constant there's nothing to worry about but just to be on the safe side the water parameters should be checked for levels of ammonia, nitrites and nitrates. Proper test results should be ammonia and nitrites=0- and nitrates 20 ppm or lower. If you don't have a test kit handy then a water sample can be brought to you local pet store and they will usually test for free.
I think the reason for the fish's action is one of wanting to take a brief recess and is no way an indication of illness.
What I would do is add some aqautium salt at a ratio of 1 teaspoon per every 5 gallons of water and add a product called Stress Coat, see link below. Both the salt and Stress Coat are very helpful to the fish and are good fish maintainance.
It would also be of great benefit to feed the fish a varied diet which should consist of goldfish flakes, frozen food and freeze dried food. And remember that the best preventative against fish illness is weekly 25% partial water changes.
Best wishes and please let me know if you have any questions.
I have tested the water and everything is as you said it should be, but he hasnt stopped doing this all day. His mouth is just stuck wide open and it looks to be quite uncomfortable, because when he gets frustrated with not being able to close it he jerks violently until it does close, only to have it open again a few seconds later. Could it be a bacterial infection?
If the fish's mouth is remaining open for extended periods of time or all the time then it would be an indication of something stuck or partially stuck in the fish's mouth.
In the case of goldfish the culprit is usually a piece of gravel but can be any other loose item.
The symptom of gaping mouth is not an indication of a bacterial infection.
Short of a minor surgical procedure there's nothing that can be done immediately to resolve the problem. The addition of aquarium salt might help break down the imbedded particle. At this point in time the best thing to happen would be for the fish to be able to finally spit the item out. So what I suggest you do is feed the fish very small bits of crushed flakes. Feeding in this manner will enable the fish to at least consume some nutrients and will also prompt the fish to try and open and close its mouth which just might help dislodge the particle that's stuck in it's mouth.
An ideal food to feed would be something that's designed to feed fry (fish babies), see link below.