Wednesday, March 08, 2006

Membuat scheduler atau proses periodik

Kita bisa menggunakan Timer seperti ini:


int initialDelay = 30000; // start after 30 seconds
int period = 5000; // repeat every 5 seconds
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
// job code here
}
};
timer.scheduleAtFixedRate(task, initialDelay, period);


Atau menggunakan EDU.oswego.cs.dl.util.concurrent.ClockDaemon seperti ini:


static protected ClockDaemon clockDaemon = new ClockDaemon();

static
{
log.debug("Setting the clockDaemon's thread factory");
clockDaemon.setThreadFactory(new ThreadFactory()
{
public Thread newThread(Runnable r)
{
Thread t = new Thread(getThreadGroup(), r, "ThreadDaemon");
t.setDaemon(true);
return t;
}
});
}

public static ThreadGroup getThreadGroup()
{
if (threadGroup.isDestroyed())
threadGroup = new ThreadGroup("Our Threads");
return threadGroup;
}


public static void main(String[] args)
{
int period = 500; //millis
clockDaemon.executePeriodically(
period,
new Runnable() {
public void run() {
System.out.println("Running...");
}
},
true);

}


Atau menggunakan Quartz, job scheduling system.

Followers