, cron, , . , . - ( ), , . , ballpark:
import java.util.*;
public abstract class TimeMonitor extends Thread
{
protected double execution_time;
protected boolean execute_at_startup;
public TimeMonitor()
{
execute_at_startup = false;
}
public TimeMonitor(double time)
{
execution_time = time;
execute_at_startup = false;
}
public void startTimer()
{
setPriority(Thread.MIN_PRIORITY);
start();
}
public void setTime(double time)
{
execution_time = time;
}
public void executeAtStartup()
{
execute_at_startup = true;
}
public void run()
{
if (execute_at_startup)
doTimedAction();
while (true)
{
long runtime = (long)(execution_time * 3600 * 1000);
long now = getTime();
long sleep = 0;
if (runtime > now)
sleep = runtime - now;
else
sleep = 24 * 3600 * 1000 - now + runtime;
try
{
Thread.sleep(sleep);
}
catch (InterruptedException e)
{
logError("Wait thread has been interrupted.", e);
continue;
}
doTimedAction();
}
}
private long getTime()
{
Calendar cal = Calendar.getInstance();
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
int millis = cal.get(Calendar.MILLISECOND);
return (hours * 3600 + minutes * 60 + seconds) * 1000 + millis;
}
private void doTimedAction()
{
try
{
performAction();
}
catch (Throwable e)
{
logError("An error occured during timed execution.", e);
}
}
protected void logError(String msg, Throwable e)
{
System.out.println(msg);
e.printStackTrace();
}
protected abstract void performAction();
}
:
TimeMonitor archiver = new TimeMonitor()
{
protected void performAction()
{
}
};
archiver.setTime(16.5);
archiver.startTimer();