简体   繁体   中英

How to make Java perform a listener task with a time delay?

Consider a Java program in which a listener triggers a certain function. Suppose a user action activates the listener a few times in a row. My problem is: how do I make Java only execute the function only once in this triggering row and only if a certain amount of time has passed after the last activation of the listener?

I've tried to look up some information both on Google and on StackExchange, but I couldn't find any hints.

(To provide some context: I'm trying to develop an Android app using the Google Maps API which includes drawing markers / marker clusters from a huge database of GPS points, wanting to only add the points in the current map view. If the user moves the map, the OnCameraChangeListener is activated quite a few times while the map still moves. However, since the database is quite huge and searching the GPS points for the given camera view might take some time, I don't want to trigger the function which adds the markers before the map view had been idle for, let's say, a second.)

You can simply hold on to those two values you described in your post:
- Boolean isFunctionRunning
- GregorianCalendar timeLastRun

Then if isFunctionRunning => false AND time since timeLastRun > 1 second, you start the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM