Vivek
Vivek

Reputation: 2101

Execute method in a scheduled manner

I want to execute a call to a particular method every minute, and it should get called with the server startup. This should be a single thread.

I tried using the CRON job , but am facing some issues with it.

Is there any way through which I can achieve it

Upvotes: 0

Views: 532

Answers (6)

Joe
Joe

Reputation: 1023

You can use Spring Tasks to achieve this easily using annotations. They are in the context jars so you shouldn't have to add any new jars to achieve this.

In your appContext add (adjust the pool-size accordingly):

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="2"/>
<task:scheduler id="myScheduler" pool-size="2"/>

You'll need to pull in the appropriate namespace too:

xmlns:task="http://www.springframework.org/schema/task"

After you do all of this you should be able to just annotate the method you want to be called. Since you want your method called every minute you should use fixedRate:

@Scheduled(fixedRate=60000)

Doing this should force the call to run on startup and every minute thereafter. The time as you can probably see is set in milliseconds.

Upvotes: 2

cesmarch
cesmarch

Reputation: 341

class DemoThread extends Thread {

public void run() {
   while(true) {
     try {
       sleep(60000);
     }
     catch(InterruptedException e) {
     }
     // call some random method here
   }
 }
} 

Init the Thread and run it.

DemoThread thread = new DemoThread();
thread.start();

Upvotes: 0

kostja
kostja

Reputation: 61538

If you are using JBoss (may also apply to other AS, I have no data on them), you may want to try the bundled quartz scheduler. It offers very finegrained job control. You don't have to use the bundled version though, and are free to use it as dependency on the AS of your choice.

Upvotes: 2

Mechkov
Mechkov

Reputation: 4324

For a similar task i am using a Quartz scheduler. It is very easy to use. My intervals are larger than a minute though, but this should not matter. You have the option to specify how many threads your scheduler will be using in a config file.

http://quartz-scheduler.org/

http://quartz-scheduler.org/api/2.0.0/

Upvotes: 2

cdc
cdc

Reputation: 2571

Use ExecutorServices...

  Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate( new Runnable()
  {

     @Override
     public void run()
     {
        // call your method here

     }
  }, 0, 1, TimeUnit.MINUTES ); 

Upvotes: 4

Matten
Matten

Reputation: 17621

Execute a particular method every minute? This sounds like you need a Timer. Have a look at this article for more information. Timer executes the method at a background thread - why is it important to execute the method within your main thread?

Upvotes: 0

Related Questions