I want to execute a method in a class say every day only once . If in a day already executed just return or else execute the method.
I want to know what happens if I exit the code will it be running in the background?
Assuming that you already know how to schedule a task to run daily the trick becomes knowing if the task has already run in that day without being prompted by the schedule.
For the desired behavior you will need to save a time-stamp (either as a variable in the java environment or as a file on the disk) of the most recent run, checking it before updating it and executing the function.
Some psuedocode:
Static bool timeManager(){
CurrentTime = getCurrentTime()
TimeStamp = getTimeStamp()
if(CurrentTime - TimeStamp > 1day-afewMinutes){
UpdateTimeStamp(CurrentTime)
return true
}else{
return false
}
}
void jobWrapper(){
if timeManager(){
doTheJob()
}else{
log("Skipping job at "+currentTime+" because job ran "+lastTime)
}
}
Edit: rollback pointed out race condition so I put the time manager in a static method. Also I realized that rounding to the second might bone you so I figured I would subtract a few minutes from the whole day to avoid tasks scheduled on 24 hour intervals from blocking each-other due to rounding...
There are many ways to do this. You can use sth like Cron job. The expression is guided here: https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm
Or you can use Quartz: http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html
Or use @Scheduled
from Spring https://spring.io/guides/gs/scheduling-tasks/
Hope this help.