Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Simplest Possible EJB 3.1 Timer

DZone's Guide to

Simplest Possible EJB 3.1 Timer

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

A timer doesn't have to be a singleton - it can be a @Stateless and even a @Stateful bean. The method doWork() will be invoked every second. There is no registration or configuration needed.

@Singleton
public class TimerService {
@EJB
HelloService helloService;

@Schedule(second="*/1", minute="*",hour="*", persistent=false)
public void doWork(){
System.out.println("timer: " + helloService.sayHello());
}
}

How to compile:

You will need the EJB 3.1 API in the classpath, or at least the @Singleton, @Schedule and @EJB annotation.

How to deploy:

Just JAR or WAR the interceptor with an EJB and put the archive into e.g: [glassfishv3]\glassfish\domains\domain1\autodeploy

Btw. the initial deployment of the entire WAR took on my machine:

INFO: Loading application SimpleTimer at /SimpleTimer
INFO: SimpleTimer was successfully deployed in 363 milliseconds.

How to use:

Another service can be easily injected to the timer and so invoked periodically:
@Stateless
public class HelloService {
public String sayHello(){
return "Hello from control: " + System.currentTimeMillis();
}
}

And: there is no XML, strange configuration, libraries, additional dependencies needed...You will find the whole executable project (tested with Netbeans 6.8 and Glassfish v3) in: http://kenai.com/projects/javaee-patterns/ [project name: SimpleTimer].

From http://www.adam-bien.com

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}