It happens in many different ways for me.
I keep notebooks that I write down any lyric/melody ideas that I have, sometimes I put something together from those. Sometimes I'll sit watching tv late at night, write down five pages of gibberish, later on I might edit those into a song.
Sometimes a song appears fully formed in my head, I just have to write it down, it's like I'm being possessed by the spirit of someone with tallent.
Once and only once I wrote a song to order. I had been asked if I had another song for the band, later that week I sat down picked up a pen, wrote the song took it to the next rehursal. Not the best thing I ever wrote, not the worst.Usually get most of my ideas when I'm too bussy to work on them. I usually play guitar when I'm writing.