Is there any way to schedule to stop or terminate a java program on a specific time. I am using java.util.timer. For example at 10pm. I know how to schedule start a java program on a specific time. Problem is I cannot figure out a way to terminate a program.
You can create a background thread (in order to not block UI) and inside you can check current hour/minutes/day
GregorianCalendar calendar = new GregorianCalendar (); // creates a new calendar instance
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR); // gets hour in 12h format
calendar.get(Calendar.MONTH); // gets month number, NOTE this is zero based!
Thread.sleep(60000) //sleep 60seconds
if(<rightTime>)
System.exit(0);
You can use TimerTask to do that, here is an example:
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class StopApp {
Timer timer = new Timer();
TimerTask StopApp = new TimerTask() {
@Override
public void run() {
System.exit(0);
}
};
public StopApp() {
//timer.schedule(exitApp, getDateDiff(new Date("get the actual time"), new Date("get the time you want to stop your app"), TimeUnit.SECONDS));
//Example
timer.schedule(StopApp, new Date(System.currentTimeMillis()+2*1000));//Exits after 2 sec of starting the app
while(true)
System.out.println("The App still turn");
}
public static Date getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
Date date=new Date(diffInMillies);
return date;//timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
new StopApp();
}
}
Check this doc: https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit(int).
System.exit(0); can do what you want.