MAJOR EDIT: Firstly you need to create a timer. I would suggest creating a public variable Timer midnightTimer = new Timer()
. Then create a new class that extends a TimerTask
:
private class PeriodicTask extends TimerTask {
@Override
public void run() {
// ... YOUR TASK (code later in this post)
}
}
Then meanwhile the program runs you probably want to launch on a Date
this following code should get midnight of whatever day it is currently:
// today
Calendar date = new GregorianCalendar();
// reset hour, minutes, seconds and millis
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
// next day
date.add(Calendar.DAY_OF_MONTH, 1);
Date midnightTonight = date.getTime();
An example can be seen here java timer task schedule
What you could do is launch your java program using the command line. This can be done through Runtime.getRuntime().exec()
(for more information look at Run .exe file from Java from file location and how to execute command line .exe file in java)
An example of this is:
try {
Runtime.getRuntime().exec("cmd.exe /c start " + PATHWAYTOYOURPROGRAM); //put here the absolute or relative path to launch the exe
} catch (IOException e) {
// ... could not launch
}
After you have relaunched your program you could then kill the original program:
System.exit(0);
EDIT: AlexlH has a good point. If you do have a error and it does crash then it will no longer run at midnight. You could also research creating a scheduled task from your java program (if one doesn't already exist) which then runs the java program again at midnight. But that would be harder to do. Here is a link that might help: