我有一个Spring Boot Web应用程序。
我希望在方法启动时启动fixedDelayed预定作业。并在someMethod
方法完成后停止预定作业。我阅读了文档,但我无法理解。 1}}在someMethod
仍然有效的情况下,我希望每隔30秒对数据库进行一次分析。
这是伪代码。有人有想法吗?
public void someMethod() {
//Start scheduledLogger() to work every 30 seconds
//...
//Do something taking long time
//Stop scheduledLogger() job
}
private void scheduledLogger() {
//Log to database
}
答案 0 :(得分:3)
您可以这样做:
public void someMethod()
{
//Start scheduledLogger() to work every 30 seconds
TimerTask tasknew = new TimerTask(){
@Override
public void run()
{
scheduledLogger();
}
};
Timer timer = new Timer();
// scheduling the task
timer.scheduleAtFixedRate(tasknew, new Date(), 3000);
//Do something taking long time
try
{
Thread.sleep(20000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
//Stop scheduledLogger() job
// terminating the timer
timer.cancel();
}
private void scheduledLogger() {
//Log to database
System.out.println("Log to database at "+new Date());
}