The above is correct, however "optimal" is probably a bit more complex than when you're able to refresh without clipping the shock. To be fully optimal you need to refresh it under the following conditions:
The existing shock falls within the time windows mentioned by Nerotox
At least 5 secs until your next Earth Shock
Lava Burst is on cooldown
2 charges of Fusion ready
Searing Totem is down
Unleash Flame is ready to use
So basically, everything that is a priority above your Lightning Bolt filler is complete - Find the sweet spot where all 6 of those are true and that would be fully optimal.
Personally, I've been trying to refresh it underneath the pandemic time, but if it is somewhat close (something like <35 instead of 22.5) and everything is lining up well (2 EF stacks and low lightning shield charges), I'll just go ahead and refresh it back up to max duration. My main reasoning for this is that if I were to wait, I could run into trouble with shock collisions where I end up wasting a number of lightning shield charges while trying to hit EF2.
The way I see it is that we are refreshing flame shock so few times a fight that even clipping a few seconds by refreshing it too early will likely not result in an extra cast. The biggest thing is making sure you are able to keep it buffed with both UF and EF2 while still using as many earth shocks as you can.