¿Hay alguna forma de programar para detener o finalizar un programa Java en un momento específico? Estoy usando java.util.timer . Por ejemplo a las 10 de la noche. Sé cómo programar el inicio de un programa Java en un momento específico. El problema es que no puedo encontrar una manera de terminar un programa.
Puede crear un hilo de fondo (para no bloquear la interfaz de usuario) y dentro puede verificar la hora/minutos/día actuales
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);Ver también https://stackoverflow.com/a/907207/6726261
Puede usar TimerTask para hacer eso, aquí hay un ejemplo:
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(); } }Consulte este documento: https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit(int) . System.exit(0); puede hacer lo que quiera.