I have a Spring Boot web application.
I want to start a fixedDelayed scheduled job when a method starts. And stop scheduled job when someMethod
method finished. I read the documentation but I couldn't understand how. I want to wirte someting to db every 30 second while someMethod
is still working.
Here is the pseudo code. Anyone has an idea?
public void someMethod() {
//Start scheduledLogger() to work every 30 seconds
//...
//Do something taking long time
//Stop scheduledLogger() job
}
private void scheduledLogger() {
//Log to database
}
You can do something like this:
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.