Utilizzando una classe java.util.Timer è possibile creare un timer e pianificarlo per l'esecuzione in un momento specifico.
Di seguito si riporta l'esempio:
//The task which you want to execute
private static class MyTimeTask extends TimerTask
{
public void run()
{
//write your code here
}
}
public static void main(String[] args) {
//the Date and time at which you want to execute
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormatter .parse("2012-07-06 13:05:45");
//Now create the time and schedule it
Timer timer = new Timer();
//Use this if you want to execute it once
timer.schedule(new MyTimeTask(), date);
//Use this if you want to execute it repeatedly
//int period = 10000;//10secs
//timer.schedule(new MyTimeTask(), date, period);
}
fonte
2012-07-06 11:31:14
dove usi 'periodo'? – Sami
ha modificato la risposta –
Timer's javadoc consiglia di utilizzare 'ScheduledThreadPoolExecutor' che è stato introdotto in Java 5: http://stackoverflow.com/a/11361397/829571 – assylias