Start a fixed schedule with a delay when the method starts and stops when finished
I have a Spring Boot web application.
I want to start a fixed scheduled job when the method runs. And terminate the scheduled job after the method completes someMethod
. I read the documentation but I couldn't figure out how to do this. I want to use the db every 30 seconds while someMethod
still working.
Here is pseudocode. Anyone have 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
}
+3
source to share
1 answer
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());
}
+3
source to share