java怎么调用dubbed,Java库类来处理“回调”的调度执行?

My program has a component - dubbed the Scheduler - that lets other components register points in time at which they want to be called back. This should work much like the Unix cron service, i. e. you tell the Scheduler "notify me at ten minutes past every full hour".

I realize there are no real callbacks in Java.

Here's my approach, is there a library which already does this stuff? Feel free to suggest improvements, too.

Register call to Scheduler passes:

a time specification containing hour, minute, second, year month, dom, dow, where each item may be unspecified, meaning "execute it every hour / minute etc." (just like crontabs)

an object containing data that will tell the calling object what to do when it is notified by the Scheduler. The Scheduler does not process this data, just stores it and passes it back upon notification.

a reference to the calling object

Upon startup, or after a new registration request, the Scheduler starts with a Calendar object of the current system time and checks if there are any entries in the database that match this point in time. If there are, they are executed and the process starts over. If there aren't, the time in the Calendar object is incremented by one second and the entreis are rechecked. This repeats until there is one entry or more that match(es). (Discrete Event Simulation)

The Scheduler will then remember that timestamp, sleep and wake every second to check if it is already there. If it happens to wake up and the time has already passed, it starts over, likewise if the time has come and the jobs have been executed.

Edit: Thanks for pointing me to Quartz. I'm looking for something much smaller, however.

解决方案

If your needs are simple, consider using java.util.Timer:

public class TimerDemo {

public static void main(String[] args) {

// non-daemon threads prevent termination of VM

final boolean isDaemon = false;

Timer timer = new Timer(isDaemon);

final long threeSeconds = 3 * 1000;

final long delay = 0;

timer.schedule(new HelloTask(), delay, threeSeconds);

Calendar calendar = Calendar.getInstance();

calendar.add(Calendar.MINUTE, 1);

Date oneMinuteFromNow = calendar.getTime();

timer.schedule(new KillTask(timer), oneMinuteFromNow);

}

static class HelloTask extends TimerTask {

@Override

public void run() {

System.out.println("Hello");

}

}

static class KillTask extends TimerTask {

private final Timer timer;

public KillTask(Timer timer) {

this.timer = timer;

}

@Override

public void run() {

System.out.println("Cancelling timer");

timer.cancel();

}

}

}

As has been noted, the ExecutorService of java.util.concurrent offers a richer API if you need it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值