• Post Reply Bookmark Topic Watch Topic
  • New Topic

do an action not more than once every n seconds

 
simone giusti
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello I would like to run a method when a condition occurs.
Since it may happen more than one time I would like to fire method not more than once every 1 o 2 seconds ...

How can I do that ??

Thanks.
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One way to achieve this keep a track of the last time action was performed (via System#currentTimeMillis()) Then check if the prescribed interval has elapsed before executing the next time
 
Liutauras Vilda
Marshal
Posts: 3413
131
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
simone giusti wrote:when a condition occurs

simone giusti wrote:Since it may happen more than one time
You mean the condition can be met more than one time during some kind of cycle, or simply loop?

Is it what you mean?
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understood the requirement as

 
simone giusti
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, this is the case.

How can I verify that condition ??

Is it what you mean?
 
Liutauras Vilda
Marshal
Posts: 3413
131
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maneesh suggested earlier the method System.currentTimeMillis(), so you could do some calculation and define how much time passed since the last time method ran.

i.e.

Probably there are more ways to do that, might even better ones. That way is very procedural. You should think towards the way encapsulating that knowledge to object so it would know if it needs to be executed or not.

Maneesh gave some idea along that, I just think that method name of example is a bit misleading, because amHungryButOnDiet() would do eating if not eaten within 4 hours, but the method name does suggest something different. Well, it isn't an easy task to come up with a good variables or methods names - takes time.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!