I'm in my mid-30s and been somewhat successful at work but my pattern has always been that I could hyperfocus on some projects for days on end and suddenly I would be bored out of my mind and not able to focus for more than 20 minutes at a time.
I've blamed and shamed myself for years, thinking I was being lazy, that my work ethic sometimes was poor/lacking, that I could just force myself into not being in that state.
Now in my mid-30s after some years of therapy my therapist and I are uncovering that I very likely have ADHD. I don't want to be medicated, I know some terrible stories from close friends who have been medicated for more than a decade and even though it helped them somewhat the side-effects were no joke after so long. Even without medicine it's really helpful to understand why I behave like this, why I can't seem to muster the willpower that my peers and friends sometimes can to be focused for hours (with breaks).
I'm only learning now, after 30+ years of life why I'm like this, I don't wish on anyone to live this long shaming and blaming yourself for supposed failures because you don't fit the mold...
Even if you don't have ADHD try some therapy, you might uncover other reasons on why you might not be able to focus for long, there might be issues with perfectionism, fears, etc. that you are not completely aware of.
Hope you find some peace, I'm slowly getting it and it's awesome to lift this burden, even if slowly.