1

I have a Timer class to response of SMS continuously.

public class MyRegularTask extends TimerTask {
    public void run() {
        Thread.sleep(1000);
        answerLeftSMS();
        // this.cancel(); I do not cancel this Timer
    }
}

Currently I am running it by a action call.

Timer time = new Timer();
MyRegularTask taskTimer = new MyRegularTask();
time.schedule(taskTimer, 0, 60000);

Is there any way to run this timer automatically, when I start Application Server (Tomcat, Glassfish) ? I am using Spring MVC (Annotation).

Mr. Mak
  • 837
  • 1
  • 11
  • 25
  • Out of curiositiy: Why `Thread.sleep(1000);` ? – Fildor Mar 02 '17 at 11:48
  • 1
    Maybe look here: http://stackoverflow.com/a/2401536/1638059 – Sebastian Mar 02 '17 at 11:49
  • 1
    This can be accomplished using [`@Scheduled`](http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html). For implementation details see [here](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html) – Bond - Java Bond Mar 02 '17 at 11:49

1 Answers1

1

Following should do the trick

@Component
public class MyRegularTask extends TimerTask {

    @PostConstruct
    public void init() {
        Timer time = new Timer();
        MyRegularTask taskTimer = new MyRegularTask();
        time.schedule(taskTimer, 0, 60000);
    }

    public void run() {
        Thread.sleep(1000);
        answerLeftSMS();
        // this.cancel(); I do not cancel this Timer
    }
}
Avinash
  • 4,115
  • 2
  • 22
  • 41