I'm often facing with task of scheduling some events. It isn't big problem to create (and make it configurable) shedule for one launche or several launches at predefined time per day, like TVT Event (howewer, there is still no universal method for handling schedule string like "3:00,9:00,15:00,21:00" in server).
But it becomes much harder to make universal configurable definitions for "3:00,9:00 in every n days", "n times in month" and so on.
I think, many people know about cron, and it looks like suitable solution for this case. After some time, spendig in search of java implementation of cron , i've found quartz library (actual version is quartz-2.0.2), that contains one class, that is able to calculate nearest launch time from cron-like string.
So, in general it looks like this:
Code: Select all
import com.l2jserver.gameserver.model.Quest; import java.util.Calendar;import org.quartz.impl.triggers.CronTriggerImpl; public class SampleEvent extends Quest{ private static final String cronDef = "0 0 3,9,15,21 ? * *"; public SampleEvent(int questId, String name, String descr) { super(questId, name, descr); long timeToStart = getNextRunInterval("cronDef"); if (timeToStart >= 0) startQuestTimer("start_event", timeToStart, null, null); } private void endEvent() { long timeToStart = getNextRunInterval("cronDef"); if (timeToStart >= 0) startQuestTimer("start_event", timeToStart, null, null); } /** * @param cronString - cron-like string * @return interval to next run for timer */ private long getNextRunInterval(String cronString) { long ret; Date currTime = Calendar.getInstance().getTime(); CronTriggerImpl tr = new CronTriggerImpl(); try { tr.setCronExpression(cronString); Date nextFireAt = tr.getFireTimeAfter(currTime); ret = nextFireAt.getTime() - System.currentTimeMillis(); } catch(Exception e) { ret = -1; } return ret; } public static void main(String[] args) { new SampleEvent(-1, "SampleEvent", "events"); }}