use of org.apache.wicket.util.time.Time in project wicket by apache.
the class Task method run.
/**
* Runs this <code>Task</code> at the given frequency. You may only call this method if the task
* has not yet been started. If the task is already running, an
* <code>IllegalStateException</code> will be thrown.
*
* @param frequency
* the frequency at which to run the code
* @param code
* the code to run
* @throws IllegalStateException
* thrown if task is already running
*/
public final synchronized void run(final Duration frequency, final ICode code) {
if (!isStarted) {
final Runnable runnable = new Runnable() {
@Override
public void run() {
// Sleep until start time
startTime.fromNow().sleep();
final Logger log = getLog();
try {
while (!stop) {
// Get the start of the current period
final Time startOfPeriod = Time.now();
if (log.isTraceEnabled()) {
log.trace("Run the job: '{}'", code);
}
try {
// Run the user's code
code.run(getLog());
} catch (Exception e) {
log.error("Unhandled exception thrown by user code in task " + name, e);
}
if (log.isTraceEnabled()) {
log.trace("Finished with job: '{}'", code);
}
// Sleep until the period is over (or not at all if it's
// already passed)
startOfPeriod.add(frequency).fromNow().sleep();
}
} catch (Exception x) {
log.error("Task '{}' terminated", name, x);
} finally {
isStarted = false;
}
}
};
// Start the thread
thread = new Thread(runnable, name + " Task");
thread.setDaemon(isDaemon);
thread.start();
// We're started all right!
isStarted = true;
} else {
throw new IllegalStateException("Attempt to start task that has already been started");
}
}
Aggregations