2

Me and my team are developing a webapplication in Java EE and we were wondering about something.

One of our classes has a certain lifecycle, it will advance through stages after certain periods of time.

How can we achieve this, how can we do, let's say, 10 minutes after the creation of the object, advance to the next stage, then after 2 hours, advance to the third stage, then after 50 minutes, advance.... and so on.

Thanks

EDIT: There won't be just ONE instance of this class, but multiple, potentially hundreds, so using a scheduled event won't provide the functionality we're looking for.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Brovoker
  • 896
  • 5
  • 16
  • Surely you've heard and/or read about scheduling mechanisms? This existing question might interest you: http://stackoverflow.com/questions/21598155/quartz-vs-java-ee-7-scheduler – Gimby Mar 04 '15 at 09:27
  • I've used scheduling mechanisms in the past, but we're talking of potentially hundreds of instances here, some of them won't even be loaded as they're persisted. They all should have seperate 'timer', I'm not looking for a scheduler, that does something at a fixed period of time, it differs for every instance. – Brovoker Mar 04 '15 at 09:33

2 Answers2

1

Lets call A the class that have a certain lifecycle.

Create an EJBTimer singleton instance (annotated with @Singleton and @Startup) holding a Set of your A instance and inject it in all your A instance. Each A instance will be in charge to register itself in the timer Set after its instantiation (for example in a @PostConstruct method).

The timer method will then iterate on each instance and check if it needs to promote its lifecycle.

Gab
  • 7,869
  • 4
  • 37
  • 68
  • But that would mean it has to check every second? I imagine that would be a huge performance issue. – Brovoker Mar 04 '15 at 11:13
  • Your lifecycle needs a second precision ? what about every 1/2 minuts or every minuts ? Imho the performance is better with one thread regularly running than many threads (one per A instance) rarely woken up – Gab Mar 04 '15 at 11:29
0

I think there is a simple solution for this.

System.currentTimeMillis() gives you the actual time in milliseconds (actually it returns 

the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. -- Java SE 7 documentation

so in the constructor of your object you can store the time of creation and periodically (like running and endless loop or something) test if enough time has passed. If yes then you can advance, else do noting.

This might seem a bit brute force, but I think it might work.

Nandor Poka
  • 281
  • 1
  • 10