When you consume it as a supplement, you are inducing what your body would normally produce anyway if you are in normal cycles and in the dark. The only difference is dosage. Your body produces very small amounts. Stores sell pills that range from 1mg to 10mg and sometimes even higher. Even 1mg is a lot. That is why they suggest you stop taking it for a couple weeks, every few months. One use of melatonin is to attempt to reset a sleep cycle if your cycles have been thrown off by travel or other circumstances. Other uses are unrelated to sleep and have interactions with the gut. Hormones are almost always multipurpose. Melatonin has no ability to keep you asleep however.
Resetting your sleep cycles can take a day, a few days or weeks depending on your age, health, hormone levels and environment.
In terms of wake cycle, your body will metabolize the melatonin and then later start producing more adrenaline. As people get older and if damage has occurred to their adrenal glands, or a myriad of other problems, then they may start producing adrenaline too soon and wake up early, feeling anxiety. This can also be a result of too much Cortisol (stress response hormone). These hormones are a complex topic all by themselves, even leaving out confounding factors.