Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I schedule a task to happen every 'N' seconds in Spring framework

How do I wire up my web.xml to have a task happen every n many seconds. Moreover, I need to have a server method refresh every 5 seconds via a method call.

Much thanks in advance

SOLVED:

http://javaprogrammingtips4u.blogspot.com/2010/05/how-to-implement-task-scheduler-job.html

like image 502
stackoverflow Avatar asked Dec 12 '11 18:12

stackoverflow


2 Answers

You can annotate the desired routine using

public class Foo {

    @Scheduled(fixedDelay=5000)
    public void Bar() {
       // ...
    }
}

But in order to for Spring for find and recognize the annotation you must declare which base package the class Foo lies in as well as configure Spring to look for scheduling tasks. Put the following in your spring XML configuration (and don't forget to import the XML namespaces contextand task).

<context:component-scan base-package="com.company.scheduling"/>
<task:annotation-driven />

Alternatively you can put @EnableScheduling before the class declaration and it does the XML config for you out of the box.

See also the context namespace and the task namespace.

like image 131
Johan Sjöberg Avatar answered Oct 13 '22 05:10

Johan Sjöberg


You can use the Quartz scheduler integration as documented here: http://static.springsource.org/spring/docs/2.0.8/reference/scheduling.html

I do not understand the 2nd part of your question about refreshing a server method.

like image 3
MK. Avatar answered Oct 13 '22 06:10

MK.