The Guardian count for a portal begins when you capture or flip it to your faction. It ends when the portal is neutralized (either from attacks or decay) or flipped. Even if all your resonators are upgraded by other agents so that you have none remaining on the portal, the count will still continue as long as you are listed as the portal’s owner. The medal will be awarded when one of your portals crosses the corresponding threshold for that tier for the first time.
The Guardian medal is one of only two that rely on maintaining a streak (the other being the Sojourner medal). It is also the only medal that can be actively denied through the actions of a sufficiently-determined opposition. There is nothing you can do to guarantee that you will get a Guardian medal; you only get it if the other faction allows it to happen. Even an ally can break your Guardian streak (by flipping the portal).
Opinions are mixed within the Ingress community with regards to the practice of “guardian hunting” (intentionally seeking out and neutralizing enemy guardian portals). Some agents consider it to be poor sportsmanship, while others consider it a legitimate tactic. Using an automated script to assist with guardian hunting is much less popular, as it constitutes a violation of the Ingress Terms of Service and is considered cheating.