2017-03-02 131 views
0

我有一个Timer类以连续响应SMS。在启动应用程序服务器上运行TimerTask

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(注释)。

+0

出curiositiy的:为什么'了Thread.sleep(1000);'? – Fildor

+1

也许看这里:http://stackoverflow.com/a/2401536/1638059 – Schlangguru

+1

这可以使用['@ Scheduled']完成(http://docs.spring.io/spring-framework/docs/current/javadoc -API /组织/ springframework的/调度/注解/ Scheduled.html)。有关实现细节,请参阅[这里](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html) –

回答

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 
    } 
} 
相关问题