David Moreno García
David Moreno García

Reputation: 4523

Instancing a new thread in Spring to execute tasks periodically

I have a dashboard made with Spring that must control some task executions. The basic idea is to have a thread to send this tasks periodically to remote trackers. How can I instance this thread? I've been reading a little and some people say that is not a good idea to use thread. Would this cause a problem with Spring life cycle? Is there another way to have a method called periodically?

Upvotes: 2

Views: 2392

Answers (6)

Basheer AL-MOMANI
Basheer AL-MOMANI

Reputation: 15327

In my case, I wanted to run a code once every month

let's say I want to execute remove function that is in EmptyScopesRemoverImpl class

so in spring xml add this

<task:scheduled-tasks>
    <task:scheduled ref="EmptyScopesRemover" method="remove" cron="0 0 0 1 * *"/>
</task:scheduled-tasks>

for more info about cron values and what it takes check https://stackoverflow.com/a/32521238/4251431

for now, that value means to run the function at the midnight on the first day of every month.

note that EmptyScopesRemover is just a bean refers to that class

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

Integrate spring with quartz and make your life easy for all the scheduled task requirements. Here is a tutorial to help you with that:

http://www.mkyong.com/spring/spring-quartz-scheduler-example/

Upvotes: 0

Vishnudev K
Vishnudev K

Reputation: 2934

IF you need a powerfull task scheduler which works perfectly with spring, use quartz scheduler.You can configure the number of threads to be used for the scheduler and much more. There is no headache of thread control here quartz scheduler manages it very well.

It can be configured in spring to work much complicated schedules like

trigger every minute from 12 am to 4 am on 1st of every month.

http://quartz-scheduler.org/ for more information.

Upvotes: 2

abishkar bhattarai
abishkar bhattarai

Reputation: 7641

You can use @Scheduled annotation Or you can create yours own thread and make it sleep and again call in periodic manner.

Upvotes: 0

Nitram76
Nitram76

Reputation: 421

When using Spring, you could try Spring's own Task Scheduling. A good tutorial can be found here.

I've used this one already and it works very well.

Upvotes: 2

kevin847
kevin847

Reputation: 1068

Spring has support for Task Scheduling. Find more information here:

E.g. you can configure scheduled task in your application context like so:

<task:scheduled-tasks scheduler="myScheduler">
  <task:scheduled ref="beanA" method="methodA" fixed-delay="5000"/>
</task:scheduled-tasks>

<task:scheduler id="myScheduler" pool-size="10"/>

Upvotes: 5

Related Questions