java-在方法开始时启动固定的延迟计划,在方法完成时停止
作者:互联网
我有一个Spring Boot Web应用程序.
我想在方法启动时启动fixedDelayed计划作业.当someMethod方法完成时,停止计划的作业.我阅读了文档,但我不明白该怎么做.我想在someMethod仍在工作时每隔30秒将dbing到db.
这是伪代码.有人有主意吗?
public void someMethod() {
//Start scheduledLogger() to work every 30 seconds
//...
//Do something taking long time
//Stop scheduledLogger() job
}
private void scheduledLogger() {
//Log to database
}
解决方法:
您可以执行以下操作:
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());
}
标签:spring-boot,quartz-scheduler,spring-scheduled,spring,java 来源: https://codeday.me/bug/20191120/2042550.html