在启动Application Server上运行TimerTask

时间:2017-03-02 11:44:03

标签: java spring timertask

我有一个Timer类来连续响应SMS。

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

目前我通过动作调用来运行它。

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

当我启动Application Server(Tomcat,Glassfish)时,有没有办法自动运行此计时器?我正在使用Spring MVC(Annotation)。

1 个答案:

答案 0 :(得分:0)

以下应该做的伎俩

@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
    }
}